Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string is not convertible to int (Swift)

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?

like image 533
quemeful Avatar asked Aug 15 '14 22:08

quemeful


People also ask

Can you convert string to Int Swift?

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.


1 Answers

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()!
like image 108
Mundi Avatar answered Oct 06 '22 02:10

Mundi