iOS Revisited: String

Hot

Post Top Ad

Showing posts with label String. Show all posts
Showing posts with label String. Show all posts

18 Oct 2017

Convert String To Int, Float, Double in Swift 4

10/18/2017 05:48:00 am 0
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.
Read More

Post Top Ad