This is the code I have (my actual code is more complex, but I simplified it down, and I still get this error):
let x = "1" as Int
Xcode says:
'String' is not convertible to 'Int'
Am I missing something or is this a beta bug?
Swift provides the function of integer initializers using which we can convert a string into an Int type. To handle non-numeric strings, we can use nil coalescing using which the integer initializer returns an optional integer.
You cannot simply cast with as
. There is a method that produces Int
explicitly.
let x = "1".toInt()
Notice that the result is of type Int?
because Swift cannot know upfront if the conversion succeeds.
println(x!)
Or:
let x = "1".toInt()!
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