We can easily convert String to Int, Float, Double using swift language.
The string must contain a number as above, otherwise it will throw an error.
The string must contain a number as above, otherwise it will throw an error.
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