Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between " as string" and "stringvalue" in swift?

I have a code :

var i : AnyObject!
i = 10
println(i as String)
println(i.stringValue)

it get crashed on as String line but runs in second i.stringValue.

What is the difference between as String and stringValue in the above lines?

like image 472
Aabid Khan Avatar asked Sep 29 '15 06:09

Aabid Khan


2 Answers

.stringValue is a way to extract Integer into string value but as String will not work for that And if you use as String then Xcode will force you to add ! with as which is not good and it will never succeed and it would crash your app. you can't cast Int to String. It will always fail. Thats why when you do as! String it crashes the app.

So casting is not a good idea here.

And here is some more ways to extract Integer into string value:

let i : Int = 5 // 5

let firstWay = i.description // "5"
let anotherWay = "\(i)"      // "5"
let thirdWay = String(i)     // "5"

Here you can not use let forthway = i.stringValue because Int Doesn't have member named stringValue

But you can do same thing with anyObject as shown below:

let i : AnyObject = 5 // 5

let firstWay = i.description // "5"
let anotherWay = "\(i)"      // "5"
let thirdWay = String(i)     // "5"
let forthway = i.stringValue // "5"  // now this will work.
like image 155
Dharmesh Kheni Avatar answered Sep 20 '22 17:09

Dharmesh Kheni


Both are casting an Int to String but this will not work anymore. In Swift 2 its not possible to do it like that.

U should use:

let i = 5
print(String(format: "%i", i))

This will specifically write the int value as a String

like image 31
Björn Ro Avatar answered Sep 18 '22 17:09

Björn Ro