Get integer value from string in swift

SwiftSwift2

Swift Problem Overview


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 String. I'd like to do something like:

var stringNumb: String = "1357"

var someNumb: Int = Int(stringNumb)

This doesn't work either:

var someNumbAlt: Int = myString.integerValue

Swift Solutions


Solution 1 - Swift

Swift 2.0 you can initialize Integer using constructor

var stringNumber = "1234"
var numberFromString = Int(stringNumber)

Solution 2 - Swift

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.

Solution 3 - Swift

In Swift 3.0

Type 1: Convert NSString to String

    let stringNumb:NSString = "1357"
    let someNumb = Int(stringNumb as String) // 1357 as integer

Type 2: If the String has Integer only

    let stringNumb = "1357"
    let someNumb = Int(stringNumb) // 1357 as integer

Type 3: If the String has Float value

    let stringNumb = "13.57"
    if let stringToFloat = Float(stringNumb){
        let someNumb = Int(stringToFloat)// 13 as Integer
    }else{
       //do something if the stringNumb not have digit only. (i.e.,) let stringNumb = "13er4"
    }

Solution 4 - Swift

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

Solution 5 - Swift

If you are able to use a NSString only.

It's pretty similar to objective-c. All the data type are there but require the as NSString addition

    var x = "400.0" as NSString 
    
    x.floatValue //string to float
    x.doubleValue // to double
    x.boolValue // to bool
    x.integerValue // to integer
    x.intValue // to int

Also we have an toInt() function added See Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l page 49

x.toInt()

Solution 6 - Swift

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.

Solution 7 - Swift

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

var myint: Int = Int(stringNumb.bridgeToObjectiveC().intValue)

Solution 8 - Swift

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
        }
    }
}

Solution 9 - Swift

A more general solution could be a extension

extension String {
    var toFloat:Float {
	    return Float(self.bridgeToObjectiveC().floatValue)
    }
    var toDouble:Double {
        ....
    }
    ....
}

this for example extends the swift native String object by toFloat

Solution 10 - Swift

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

Solution 11 - Swift

8:1 Odds(*)

var stringNumb: String = "1357"
var someNumb = Int(stringNumb)

or

var stringNumb: String = "1357"
var someNumb:Int? = Int(stringNumb)

Int(String) returns an optional Int?, not an Int.


Safe use: do not explicitly unwrap

let unwrapped:Int = Int(stringNumb) ?? 0

or

if let stringNumb:Int = stringNumb { ... }

(*) None of the answers actually addressed why var someNumb: Int = Int(stringNumb) was not working.

Solution 12 - Swift

Simple but dirty way

// Swift 1.2
if let intValue = "42".toInt() {
    let number1 = NSNumber(integer:intValue)
}
// Swift 2.0
let number2 = Int(stringNumber)

// Using NSNumber
let number3 = NSNumber(float:("42.42" as NSString).floatValue)

The extension-way

This is better, really, because it'll play nicely with locales and decimals.

extension String {
    
    var numberValue:NSNumber? {
        let formatter = NSNumberFormatter()
        formatter.numberStyle = .DecimalStyle
        return formatter.numberFromString(self)
    }
}

Now you can simply do:

let someFloat = "42.42".numberValue
let someInt = "42".numberValue

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLoganView Question on Stackoverflow
Solution 1 - SwiftBruceView Answer on Stackoverflow
Solution 2 - SwiftCW0007007View Answer on Stackoverflow
Solution 3 - SwiftRajamohan SView Answer on Stackoverflow
Solution 4 - SwiftNate CookView Answer on Stackoverflow
Solution 5 - SwiftJohn RiselvatoView Answer on Stackoverflow
Solution 6 - SwiftswiftBoyView Answer on Stackoverflow
Solution 7 - SwiftConnorView Answer on Stackoverflow
Solution 8 - Swifttimo-haasView Answer on Stackoverflow
Solution 9 - SwiftloopmastaView Answer on Stackoverflow
Solution 10 - SwiftPablo RuanView Answer on Stackoverflow
Solution 11 - SwiftSwiftArchitectView Answer on Stackoverflow
Solution 12 - SwiftKevin RView Answer on Stackoverflow