Literal string versus string "string" in quick

Playing with speed, I found this amazing:

"123".integerValue // <= returns 123 var x = "123" x.integerValue // <= Error: String does not have a member named integerValue 

Can someone explain?

+6
source share
4 answers

I assume that in the first example, the compiler uses the integerValue call as additional information for type inference (a choice between NSString and Swift String).

The second example probably uses the Swift line by default because it does not evaluate multiple lines.

+6
source

I believe this is an example of type inference in action. When you do this: the "123".integerValue compiler detects that in this case you want to use NSString (which it also does when you use string literals as arguments for objective-c functions.

A similar example:

 // 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 
+1
source

Use .toInt()

 var x = "123" var num: Int = x.toInt() 
+1
source

If you do:

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

he will not show this error.

I think your first example will automatically select that you want to use NSString, since NSString only has this .integerValue call.

The second example probably does not work, because he is not informed what it is, and instead they decide to use a fast line.

0
source

Source: https://habr.com/ru/post/970249/


All Articles