Skip to content

Convert a String into an Int, Float, Double in Swift

Convert a String into an Int, Int8, Int16, Int32, and Int64

The Swift type Int, and related Int8, Int16, Int32, and Int64, contain a constructor that takes in a String argument and return an optional parsed value.

swift
// Convert String to Int
let strInt = "10"
let int = Int(strInt)
let int8 = Int8(strInt)
let int16 = Int16(strInt)
let int32 = Int32(strInt)
let int64 = Int64(strInt)

let invalidStrInt = "hello"
let invalidInt = Int(invalidStrInt) // nil

Convert a String into a UInt, UInt8, UInt16, UInt32, and UInt64

Just like Int, the Swift type UInt, and related UInt8, UInt16, UInt32, and UInt64, contain a constructor that takes in a String argument and return an optional parsed value.

swift
// Convert String to UInt
let strUInt = "10"
let uint = UInt(strUInt)
let uint8 = UInt8(strUInt)
let uint16 = UInt16(strUInt)
let uint32 = UInt32(strUInt)
let uint64 = UInt64(strUInt)

let strNegativeUInt = "-10"
let negtiveUInt = UInt(strNegativeUInt) // nil

let invalidStrUInt = "hello"
let invalidUInt = UInt(invalidStrUInt) // nil

Convert a String into a Float, Double

Swift type Float and Double contain a constructor that takes in a String argument and return an optional parsed value.

swift
// Convert a String to Double,Float
let strfloat = "3.14"
let strdouble = "3.1415926"
let stroutdouble = "3.14159265358979323846"
let invalidStrFloat = "hello"

let float1 = Float(strfloat)                // "3.14" -> 3.14 
let float2 = Float(strdouble)               // "3.1415926" -> 3.141593
let float3 = Float(stroutdouble)            // "3.14159265358979323846" -> 3.141593
let float4 = Float(invalidStrFloat)         // "hello" -> nil

let double1 = Double(strfloat)              // "3.14" -> 3.14 
let double2 = Double(strdouble)             // "3.1415926" -> 3.1415926
let double3 = Double(stroutdouble)          // "3.14159265358979323846" -> 3.141592653589793
let double4 = Double(invalidStrFloat)       // "hello" -> nil