Converting String to Int with Swift

前端 未结 30 1595
小鲜肉
小鲜肉 2020-11-22 06:59

The application basically calculates acceleration by inputting Initial and final velocity and time and then use a formula to calculate acceleration. However, since the value

30条回答
  •  没有蜡笔的小新
    2020-11-22 07:17

    You can use NSNumberFormatter().numberFromString(yourNumberString). It's great because it returns an an optional that you can then test with if let to determine if the conversion was successful. eg.

    var myString = "\(10)"
    if let myNumber = NSNumberFormatter().numberFromString(myString) {
        var myInt = myNumber.integerValue
        // do what you need to do with myInt
    } else {
        // what ever error code you need to write
    }
    

    Swift 5

    var myString = "\(10)"
    if let myNumber = NumberFormatter().number(from: myString) {
        var myInt = myNumber.intValue
        // do what you need to do with myInt
      } else {
        // what ever error code you need to write
      }
    

提交回复
热议问题