Playing with swift I found this surprising:
"123".integerValue // <= returns 123
var x = "123"
x.integerValue // <= Error: String does not have a member named integerValue
Can someone explain?
My guess is that in the first example the compiler uses the call to integerValue
as additional information to infer the type (choosing between NSString and a Swift String).
In the second example it probably defaults to a Swift String because it doesn't evaluate multiple lines.
I believe this is an example of type inference in action. When you do: "123".integerValue
the compiler detects that in this case you want to use an NSString
(which it also does when you use string literals as arguments to objective-c functions.
A similar example is:
// x is an Int
let x = 12
// here we tell the compiler that y is a Double explicitly
let y: Double = 12
// z is a Double because 2.5 is a literal Double and so "12" is also
// parsed as a literal Double
let z = 12 * 2.5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With