Get integer value from string in swift

后端 未结 12 1781
小蘑菇
小蘑菇 2020-11-27 17:14

So I can do this:

var stringNumb: NSString = \"1357\"

var someNumb: CInt = stringNumb.intValue

But I can\'t find the way to do it w/ a

相关标签:
12条回答
  • 2020-11-27 17:47

    Convert String to Int in Swift 2.0:

    var str:NSString = Data as! NSString
    var cont:Int = str.integerValue
    

    use .intergerValue or intValue for Int32

    0 讨论(0)
  • 2020-11-27 17:53

    The method you want is toInt() -- you have to be a little careful, since the toInt() returns an optional Int.

    let stringNumber = "1234"
    let numberFromString = stringNumber.toInt()
    // numberFromString is of type Int? with value 1234
    
    let notANumber = "Uh oh"
    let wontBeANumber = notANumber.toInt()
    // wontBeANumber is of type Int? with value nil
    
    0 讨论(0)
  • 2020-11-27 17:54

    above answer didnt help me as my string value was "700.00"

    with Swift 2.2 this works for me

    let myString = "700.00"
    let myInt = (myString as NSString).integerValue
    

    I passed myInt to NSFormatterClass

    let formatter = NSNumberFormatter()
    formatter.numberStyle = .CurrencyStyle
    formatter.maximumFractionDigits = 0
    
    let priceValue = formatter.stringFromNumber(myInt!)!
    
    //Now priceValue is ₹ 700
    

    Thanks to this blog post.

    0 讨论(0)
  • 2020-11-27 17:54

    You can bridge from String to NSString and convert from CInt to Int like this:

    var myint: Int = Int(stringNumb.bridgeToObjectiveC().intValue)
    
    0 讨论(0)
  • 2020-11-27 17:55

    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.

    0 讨论(0)
  • 2020-11-27 17:55

    I wrote an extension for that purpose. It always returns an Int. If the string does not fit into an Int, 0 is returned.

    extension String {
        func toTypeSafeInt() -> Int {
            if let safeInt = self.toInt() {
                return safeInt
            } else {
                return 0
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题