Get integer value from string in swift Get integer value from string in swift swift swift

Get integer value from string in swift


Swift 2.0 you can initialize Integer using constructor

var stringNumber = "1234"var numberFromString = Int(stringNumber)


I'd use:

var stringNumber = "1234"var numberFromString = stringNumber.toInt()println(numberFromString)

Note toInt():

If the string represents an integer that fits into an Int, returns the corresponding integer.


In Swift 3.0

Type 1: Convert NSString to String

    let stringNumb:NSString = "1357"    let someNumb = Int(stringNumb as String) // 1357 as integer

Type 2: If the String has Integer only

    let stringNumb = "1357"    let someNumb = Int(stringNumb) // 1357 as integer

Type 3: If the String has Float value

    let stringNumb = "13.57"    if let stringToFloat = Float(stringNumb){        let someNumb = Int(stringToFloat)// 13 as Integer    }else{       //do something if the stringNumb not have digit only. (i.e.,) let stringNumb = "13er4"    }