How to convert String? to Integer

I've been searching for a solution for this for days, and I've found that previous Swift versions had a function toInt() which does exactly what I need, but it no longer exists, and in its place, int().. But the int() doesn't work when my string is an optional string. How can I fix this? Is there another way around this?

Creating your own doesn't sound too difficult....


func toInt(s: String?) -> Int {
  var result = 0
  if let str: String = s,
  i = Int(str) {
      result = i
  }
  return result
}


I don't know if there's a way to extend an "Optional" to make it easier to use.

In general, you need to (safely) unwrap the optional string. There are several ways to do this. Int(String) returns an optional as well, so it kind of depends how you want to handle that part of it. The following examples assume you want the result to be 0 if the optional string is nil, or if the string can't be converted to an int, and that you don't want the result stored in an optional.

You could use a ternary expression (expression before ? is evaluted for true/false; if true, expression before : is used; if false expression after : is used):

let i = (optionalString == nil || Int(optionalString!) == nil) ? 0 : Int(optionalString!)!

Note that the order of the two parts of the or statement are important; if you reverse them and optionalString is nil, it will crash.

You could use if..let:

var i = 0
if let unwrappedString = optionalString {
    if let unwrappedInt = Int(unwrappedString) {
        i = unwrappedInt
    }
}

There are probably several other ways to do this as well.

I tried something like that already but at your line 4, where there's an Int(str), I get the error "cannot find an initializer for type 'int' that accepts an argument list of type '(String)'

If I paste what I wrote into a playground, it works with Swift 2.1 (Xcode 7.2).

What versions of things are you working with?

If you don't care whether the resulting Int is an optional:


let int = Int(optionalString ?? "")


If you do care:


let int = Int(optionalString ?? 0)

Oh, wow. That might be it. Just realized I was still on xcode 6.x. I'm updating it right now, and try your code out. I'll let you know if it works!

That second line won't compile; "Binary operator '??' cannot be applied to operands of type 'String?' and 'Int'.


The following works ONLY if the optional string really contains an integer:

let j = Int(s ?? "0")!


EDIT: The following works no matter what is in the optional string:

let j = Int(s ?? "0") ?? 0

Which is kind of strange, because Int(s ?? "0") returns an optional, but 0 is not optional, and Swift creates j as non-optional and doesn't complain.

I suppose to be explicit, you should write it as:

let j: Int = Int(s ?? "0") ?? 0


EDIT #2:

After thinking about it some more, it isn't strange; it works for the same reason the s ?? "0" part of our simple example works (where s is optional but "0" is not). The point of using a ?? b is that a is optional, and the docs say ?? unwraps a if it isn't nil, so if you let Swift infer the result type, b and the result are the same "optionalness". For example the result (j) will be Int here:

let j = Int(s ?? "0") ?? 0

and Int? here:

let k: Int? = 0
let j - Int(s ?? "0") ?? k

Sorry. you're right... was moving fast.


This would be safer:


let i = Int(optString ?? "") ?? 0

note: even if the question is to force conversion to Int, DO note You are breaking ALL the good deriving from "optionalilty": it's FAR better to propagate nil and manage optionals, so you can get a better and legant logic passing around values.

As in Apple docs, absence of value is very different form a default value.

How to convert String? to Integer
 
 
Q