How to convert a given string to int in Swift
We can convert a string to an int in swift by using the built-in Int()
initializer syntax by passing the string as an argument to it.
In this example, we are converting the string "929"
to an int value 929
:
let str = "929"
let convertedNumber = Int(str) ?? 0
print(convertedNumber)
Output:
929
In the above code, we have added the Int(str) ?? 0
it means the Int()
returns an optional value 0
if it fails to convert the given string into an int.