0

In swift playground, we need cast Int to CGFloat explicitly, otherwise playground will say ERROR.

For example,

let someInt: Int = 3
let someFloat: CGFloat = CGFloat(someInt)

When use CGRectMake(...), we must cast Int to CGFloat.

Why can't happen implicitly ? What is the consideration to design this way ? Thanks for discussion here.

Forrest
  • 122,703
  • 20
  • 73
  • 107
  • 1
    That's the way it is. There is no automatic coercion of types, even numeric types, of variables in Swift. Are you asking _why_? That's a matter of opinion and isn't appropriate to Stack Overflow. – matt Sep 19 '14 at 01:03
  • 1
    Further discussion of this topic here: http://stackoverflow.com/questions/24108827/swift-numerics-and-cgfloat-cgpoint-cgrect-etc – matt Sep 19 '14 at 01:04
  • it is basically turn implicit conversion warning (in other languages) to error – Bryan Chen Sep 19 '14 at 01:25

1 Answers1

1

Int and CGFloat are different types, so you can't assign one to the other in Swift. Also, you aren't actually casting in these cases. A swift cast uses the as or as? keyword. Instead, you're creating a new CGFloat instance from someInt.

I'm not exactly sure why they designed the language this way, but as matt said the reasoning behind these choices isn't on topic for Stack Overflow.

Connor Pearson
  • 63,902
  • 28
  • 145
  • 142