Converting String to Int with Swift

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

    Swift 3.0

    Try this, you don't need to check for any condition I have done everything just use this function. Send anything string, number, float, double ,etc,. you get a number as a value or 0 if it is unable to convert your value

    Function:

    func getNumber(number: Any?) -> NSNumber {
        guard let statusNumber:NSNumber = number as? NSNumber else
        {
            guard let statString:String = number as? String else
            {
                return 0
            }
            if let myInteger = Int(statString)
            {
                return NSNumber(value:myInteger)
            }
            else{
                return 0
            }
        }
        return statusNumber
    }
    

    Usage: Add the above function in code and to convert use let myNumber = getNumber(number: myString) if the myString has a number or string it returns the number else it returns 0

    Example 1:

    let number:String = "9834"
    print("printing number \(getNumber(number: number))")
    

    Output: printing number 9834

    Example 2:

    let number:Double = 9834
    print("printing number \(getNumber(number: number))")
    

    Output: printing number 9834

    Example 3:

    let number = 9834
    print("printing number \(getNumber(number: number))")
    

    Output: printing number 9834

提交回复
热议问题