Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Literal String vs. `String` in swift

Tags:

ios

swift

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?

like image 279
gwcoffey Avatar asked Jun 03 '14 15:06

gwcoffey


2 Answers

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.

like image 50
lassej Avatar answered Oct 06 '22 00:10

lassej


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
like image 40
Jiaaro Avatar answered Oct 06 '22 01:10

Jiaaro