The difference between var someString = "Some String", var someString: String = "Some String", var someString = "Some String" as a string

Can someone explain the difference to me

var someString = "Some String" var someString: String = "Some String" var someString = "Some String" as String var someString = "Some String" as! String var someString = "Some String" as? String 
+5
source share
1 answer
 let someString = "Some String" let someString: String = "Some String" 

There are two for this:

Performance difference from zero. At compile time, Swift infers the type and writes it for you. But after compilation, both statements are identical.

 let someString = "Some String" as String 

Indicates that you produce someString value in a string if it is not a string.

 let someString = "Some String" as! String 

Indicates that you are forcibly throwing "Some String" as a string, but if it does not convert to a string, the application will crash.

 let someString = "Some String" as? String 

Assumes that you randomly throw "Some String" on a string, if it does not convert to a string, then it will return zero, but there will be no crash at that point.

Over the past 3 statements It will compile and work, but it is definitely wrong to use String for String. no need to throw a String into a String .

And the last 2 as? and as! will always be successful in your case.

Consider the following example:

 let stringObject: AnyObject = "Some String" let someString3 = stringObject as! String let someString5 = stringObject as? String 

This is when you will need to quit. Use as! only if you know this is a string. And use as? if you do not know that it will be a string or not.

disables only as! , if you are sure that otherwise use conditional listing as follows:

 if let someString5 = stringObject as? String { println(someString5) } 
+15
source

All Articles