The string is not converted to int (Swift)

This is the code that I have (my actual code is more complicated, but I simplified it 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?

+5
source share
2 answers

You cannot just draw with as . There is a method that explicitly expresses Int .

 let x = "1".toInt() 

Note that the result is of type Int? , because Swift cannot know in advance if the conversion is successful.

 println(x!) 

Or:

 let x = "1".toInt()! 
+9
source

Hope this helps you how it should be

 let x = "1".toInt() 
+1
source

Source: https://habr.com/ru/post/1200454/


All Articles