Converting String to Int with Swift

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

提交回复
热议问题