Convert String To Int, Float, Double in Swift 4 - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

18 Oct 2017

Convert String To Int, Float, Double in Swift 4

We can easily convert String to Int, Float, Double using swift language.

Convert String To Int, Float, Double in Swift 4

String to Int:

By using Int constructor we can convert as follow:

let ageString = "25"

if let age = Int(ageString) {
    print(age)
} else {
    print("Not a valid string for conversion")
}

String to Float:

Same as Int, here we use Float constructor as follow:

let distanceString = "4.54" //in miles

if let distance = Float(distanceString) {
    print(distance)
} else {
    print("Not a valid string for conversion")
}

The string must contain a number as above, otherwise it will throw an error.

String to Double:

Same as Float, here we use Double constructor as follow:

let distanceString = "4.8765878" //in miles

if let distance = Double(distanceString) {
    print(distance)
} else {
    print("Not a valid string for conversion")
}

The string must contain a number as above, otherwise it will throw an error.

No comments:

Post a Comment

Post Top Ad