lomokat
lomokat

Reputation: 383

Unwrapping Optional Int in Swift

The API response I am working with returns a total amount. It supports multiple different currencies, so sometimes the currency symbol will be at the front (ex. $20.00) or at the end (ex. 20.00€). I am doing a check to see if the first char of the value is an int. In this specific case, the value "20.00€" is being returned. firstChar is "2" :

DOES NOT WORK:

let firstNumOpt: Int? = String(firstChar).toInt()
if let num = firstNumOpt { //20.00€
   NSLog("Total: \(total)")        
}

WORKS:

if let num = String(firstChar).toInt() { //20.00€
    NSLog("Total: \(total)")        
}

Can someone explain why the first code block does not work? Both ways seem identical to me.
Some debug info:

(lldb) po firstNumOpt
2
{
value = 2
}

(lldb) po num
411432864

Upvotes: 2

Views: 820

Answers (1)

Ian MacDonald
Ian MacDonald

Reputation: 14030

Note: This isn't really an answer, but I needed to post code to describe what was working.

I'm not sure that your error is in the code that you've posted. Here is some code that I just ran in an empty playground:

func test(str: String) {
  let firstNumOpt: Int? = String(str[str.startIndex]).toInt()
  if let anum = firstNumOpt {
    print("First worked on \(str)")
  }
  if let bnum = String(str[str.startIndex]).toInt() {
    print("Second worked on \(str)")
  }
}

test("20.00€") // prints "First worked on 20.00€" and "Second worked on 20.00€"
test("$20.00") // doesn't print anything

Upvotes: 1

Related Questions