Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between var someString = “Some String”, var someString: String = “Some String”, var someString = “Some String” as string

Tags:

ios

swift

Can anyone please explain me the difference

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
like image 804
Vakas Avatar asked Jun 06 '15 04:06

Vakas


1 Answers

let someString = “Some String”
let someString: String = “Some String”

For this two:

There’s zero runtime efficiency difference between the two. During compilation, Swift is inferring the type and writing it in for you. But once compiled, the two statements are identical.

let someString = “Some String” as String

Means you are casting someString value to string if it is not string.

let someString = “Some String” as! String

Means you are forcibly casting “Some String” as a string but if it is not convertible to string then it will crash the app.

let someString = “Some String” as? String

Means you are optionally casting “Some String” to string means if it is not convertible to string then it will return nil but wont crash at this point.

For last 3 Statement It would compile and work but it is definitely wrong to cast String to String. there is no need to cast a String to String.

And the the last 2 as? and as! would always succeed in your case.

Consider below example:

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

This is when you will need to cast. Use as! only if you know it is a string. And use as? if you doesn't know that it will be string or not.

only force downcast with as! if you are sure otherwise use conditional cast like this:

if let someString5 = stringObject as? String {
    println(someString5)
}
like image 148
Dharmesh Kheni Avatar answered Oct 30 '22 09:10

Dharmesh Kheni