137

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
timbo
  • 13,244
  • 8
  • 51
  • 71
Logan
  • 52,262
  • 20
  • 99
  • 128
  • 1
    `var someNumb: Int? = Int(stringNumb)` or `var someNumb = Int(stringNumb)` – SwiftArchitect Feb 03 '16 at 21:39
  • Note that integerValue cleans dirty strings, if needed. For example these strings all result in 1357: "00001357", " 1357 ", "+ 1357", "1357.02", "1357 Main St" – Marcy Jun 03 '22 at 19:08

12 Answers12

181

Swift 2.0 you can initialize Integer using constructor

var stringNumber = "1234"
var numberFromString = Int(stringNumber)
Bruce
  • 8,609
  • 8
  • 54
  • 83
94

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.

idmean
  • 14,540
  • 9
  • 54
  • 83
CW0007007
  • 5,681
  • 4
  • 26
  • 31
  • 5
    This worked, although if you declare the var explicitly, you need to add an exclamation point: `var someNumb: Int = stringNumber.toInt()!` as @NateCook pointed out – Logan Jun 03 '14 at 15:44
  • I'm not declaring it explicitly. The compiler knows that numberFromString should be an int because it's initialised as one... – CW0007007 Jun 03 '14 at 15:45
  • I know that you are not, but I am. I had to make that adjustment to do so. Your code is correct, just adding it as a comment. – Logan Jun 03 '14 at 15:47
  • Yes it only returns a value if the value fits into an Int as the note points out. Otherwise it returns nil... – CW0007007 Jun 03 '14 at 15:47
  • Ahh I see, sorry misunderstood. There's no need for you to explicitly declare it ? – CW0007007 Jun 03 '14 at 15:48
  • I know there's no need, I'm just experimenting w/ different stuff while I'm learning :) – Logan Jun 03 '14 at 15:50
  • Ah ok. Yeah It's good to experiment. Been playing with it myself. I really like it. Bye Bye Obj-C. – CW0007007 Jun 03 '14 at 15:51
  • 5
    Instead of putting `!` on the call, you can declare your variable as optional: `someNumb: Int? = stringNumber.toInt()`. Then the type safety system will be aware that `foo` may not exist. Putting `!` will of course crash if your string can't convert to a number. – gwcoffey Jun 03 '14 at 15:54
  • @gwcoffey that's correct, if you leave the ! or ? our and don't implicitly cast it it just returns nil with an invalid int i.e. "wqeqweq". But you're correct that if you add ! after toInt() it will crash at runtime. Also putting ? at the end prevents the crash. – CW0007007 Jun 03 '14 at 15:57
  • I'm guessing you would only use var numberFromString : Int = XXX in the event that the initialising operation was returning 'AnyObject'? – CW0007007 Jun 03 '14 at 15:59
  • it says **'toInt()' is unavailable: Use Int() initializer** – swiftBoy Jul 29 '16 at 10:20
18

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"
    }
Rajamohan S
  • 7,229
  • 5
  • 36
  • 54
  • The code for "Type 3" is not ideal. Instead of checking of `stringToFloat` is `!= nil`, you should use `if let`. – rmaddy Jul 17 '17 at 15:45
11

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
Nate Cook
  • 92,417
  • 32
  • 217
  • 178
6

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()
John Riselvato
  • 12,854
  • 5
  • 62
  • 89
4

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.

swiftBoy
  • 35,607
  • 26
  • 136
  • 135
  • 1
    This question is about getting an *integer* from a String. In your case, you don't have an Int, you have a Double. In Swift, just use `Double()` the same way we're using `Int()`. No need to use bridging to NSString. – Eric Aya Jul 29 '16 at 11:45
  • Hey @EricD thanks for your suggestion but "**I wanted Integer only** as I am passing Int to NSNumberFormatter class for currency convertor". – swiftBoy Jul 29 '16 at 11:51
  • 1
    Well in this case you can use `Double()` *then* use `Int()`. Like this: `if let d = Double("700.00") { let i = Int(d); print (i) }` :) – Eric Aya Jul 29 '16 at 11:54
3

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

var myint: Int = Int(stringNumb.bridgeToObjectiveC().intValue)
Connor Pearson
  • 63,902
  • 28
  • 145
  • 142
1

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
        }
    }
}
timo-haas
  • 231
  • 1
  • 5
  • 3
    This can be written more succinctly as `return self.toInt() ?? 0`. It's probably better to just write it that way inline rather than having an extension method for this. – jlong64 Jan 13 '15 at 03:15
0

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

loopmasta
  • 1,693
  • 3
  • 14
  • 19
0

Convert String to Int in Swift 2.0:

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

use .integerValue or intValue for Int32

Marcy
  • 4,611
  • 2
  • 34
  • 52
Pablo Ruan
  • 1,681
  • 1
  • 17
  • 12
0

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.

SwiftArchitect
  • 47,376
  • 28
  • 140
  • 179
0

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
Kevin R
  • 8,230
  • 4
  • 41
  • 46