To convert a String to an Integer in Swift, you can use the Int
initializer.
In this example,
str
with a string value of "123"
.Int
initializer to convert it to an integer and store the result in the constant number
.Int
initializer attempts to convert the string to an integer, returning nil
if the conversion fails.number
using print()
.let str = "123"
if let number = Int(str) {
print("Integer value: \(number)")
}
Integer value: 123
In this example,
str
with a string value of "456"
.Int
initializer to convert it to an integer and store the result in the constant number
.Int
initializer attempts to convert the string to an integer, returning nil
if the conversion fails.number
using print()
.let str = "456"
if let number = Int(str) {
print("Integer value: \(number)")
}
Integer value: 456
In this tutorial, we learned How to Convert String to Integer in Swift language with well detailed examples.