6

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?

2
  • It looks like "123".integerValue is bridging it over to NSString. var x = "123"; (x as NSString).integerValue // <= returns 123 Commented Jun 3, 2014 at 15:51
  • @MalcolmJarvis Or the more verbose: x.bridgeToObjectiveC().integerValue Commented Jun 3, 2014 at 16:01

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

To add to this, you can explicitly type the variable var x:NSString = "123" to resolve the issue
I came to the same conclusion. Didn't realize things like method calls would factor into inference, but it makes sense. Thanks!
1

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

Comments

1

Use .toInt()

var x = "123"

var num: Int = x.toInt()

1 Comment

Yeah I know that. I was just surprised by the result I was seeing.
0

If you do:

var x = "123" as NSString
x.integerValue

var x : NSString = "123" // or this as Sulthan suggests

it won't show that error.

I think your first example is automatically picking up that you want to use a NSString as NSString only has this .integerValue call.

The second example is probably failing because it's not being told what it is and deciding to use a swift string instead.

1 Comment

var x : NSString = "123" would probably be better

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.