Aabid Khan
Aabid Khan

Reputation: 1237

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?

Upvotes: 7

Views: 4933

Answers (3)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71852

.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.

Upvotes: 10

Bhavin Bhadani
Bhavin Bhadani

Reputation: 22374

with as String, you can not cast the value but you define that the variable contains String but in you case it is Int.so it crashes.

while the other way i.e. of i.stringValue cast your value into String.So it doesn't gives you any crash and successfully cast into String value.

Note: As you are using AnyObject, variable have member stringvalue...but Int doesn't have...To cast Int value check out @Dharmesh Kheni answer

Upvotes: 1

Björn Ro
Björn Ro

Reputation: 780

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

Upvotes: 2

Related Questions