Converting String to Int with Swift

前端 未结 30 1237
小鲜肉
小鲜肉 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:15

    Swift 5.0 and Above

    Working

    In case if you are splitting the String it creates two substrings and not two Strings . This below method will check for Any and convert it t0 NSNumber its easy to convert a NSNumber to Int, Float what ever data type you need.

    Actual Code

    //Convert Any To Number Object Removing Optional Key Word.
    public func getNumber(number: Any) -> NSNumber{
     guard let statusNumber:NSNumber = number as? NSNumber  else {
        guard let statString:String = number as? String else {
            guard let statSubStr : Substring = number as? Substring else {
                return 0
            }
            if let myInteger = Int(statSubStr) {
                return NSNumber(value:myInteger)
            }
            else{
                return 0
            }
        }
    
        if let myInteger = Int(statString) {
            return NSNumber(value:myInteger)
        }
        else if let myFloat = Float(statString) {
            return NSNumber(value:myFloat)
        }else {
            return 0
        }
    }
    return statusNumber }
    

    Usage

    if let hourVal = getNumber(number: hourStr) as? Int {
    
    }
    

    Passing String to check and convert to Double

    Double(getNumber(number:  dict["OUT"] ?? 0)
    
    0 讨论(0)
  • 2020-11-22 07:16

    Basic Idea, note that this only works in Swift 1.x (check out ParaSara's answer to see how it works in Swift 2.x):

        // toInt returns optional that's why we used a:Int?
        let a:Int? = firstText.text.toInt() // firstText is UITextField
        let b:Int? = secondText.text.toInt() // secondText is UITextField
    
        // check a and b before unwrapping using !
        if a && b {
            var ans = a! + b!
            answerLabel.text = "Answer is \(ans)" // answerLabel ie UILabel
        } else {
            answerLabel.text = "Input values are not numeric"
        }
    

    Update for Swift 4

    ...
    let a:Int? = Int(firstText.text) // firstText is UITextField
    let b:Int? = Int(secondText.text) // secondText is UITextField
    ...
    
    0 讨论(0)
  • 2020-11-22 07:16

    Useful for String to Int and other type

    extension String {
            //Converts String to Int
            public func toInt() -> Int? {
                if let num = NumberFormatter().number(from: self) {
                    return num.intValue
                } else {
                    return nil
                }
            }
    
            //Converts String to Double
            public func toDouble() -> Double? {
                if let num = NumberFormatter().number(from: self) {
                    return num.doubleValue
                } else {
                    return nil
                }
            }
    
            /// EZSE: Converts String to Float
            public func toFloat() -> Float? {
                if let num = NumberFormatter().number(from: self) {
                    return num.floatValue
                } else {
                    return nil
                }
            }
    
            //Converts String to Bool
            public func toBool() -> Bool? {
                return (self as NSString).boolValue
            }
        }
    

    Use it like :

    "123".toInt() // 123
    
    0 讨论(0)
  • 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
      }
    
    0 讨论(0)
  • 2020-11-22 07:17

    Use this:

    // get the values from text boxes
        let a:Double = firstText.text.bridgeToObjectiveC().doubleValue
        let b:Double = secondText.text.bridgeToObjectiveC().doubleValue
    
    //  we checking against 0.0, because above function return 0.0 if it gets failed to convert
        if (a != 0.0) && (b != 0.0) {
            var ans = a + b
            answerLabel.text = "Answer is \(ans)"
        } else {
            answerLabel.text = "Input values are not numberic"
        }
    

    OR

    Make your UITextField KeyboardType as DecimalTab from your XIB or storyboard, and remove any if condition for doing any calculation, ie.

    var ans = a + b
    answerLabel.text = "Answer is \(ans)"
    

    Because keyboard type is DecimalPad there is no chance to enter other 0-9 or .

    Hope this help !!

    0 讨论(0)
  • 2020-11-22 07:18

    Convert String value to Integer in Swift 4

    let strValue:String = "100"
    let intValue = strValue as! Int
    var intValueFromString:Int = strValue as! Int
    or
    var intValueFromString = Int(strValue)!
    
    0 讨论(0)
提交回复
热议问题