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 secondi.stringValue
.
What is the difference between as String
and stringValue
in the above lines?
.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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With