Giant Elk
Giant Elk

Reputation: 5685

Optional issue converting String to Int in Swift 1.2

I can't figure out why this 'optional' isn't working in scenario 1, but without the optional ? it works in scenario 2.

Using Swift v 1.2, xCode 6.2

var stuff = "6t"

// SCENARIO 1
// Why is this failing when stuff contains non-digit characters?
// i.e. it works if stuff = "45".
if let value: Int? = stuff.toInt() {
    println("value \(value!)")
}

// SCENARIO 2    
// This works!
if let value = stuff.toInt() {
    println("val3 \(value)")
}

For Reference also see these SO Answers: * I wonder if the Sift 1.2 example/Answer here is just plain wrong? Swift - Converting String to Int

Converting String to Int in Swift

Upvotes: 0

Views: 100

Answers (2)

Luca Angeletti
Luca Angeletti

Reputation: 59496

The first IF is always true.

Infact in both cases:

  1. when the toInt() returns a valid Int
  2. when returns nil

the if let will succeed (and yes, the first IF is useless).

Specifically in your code toInt() returns nil in both scenarios. But in your first scenario you are simply accepting nil as a valid value to enter the THEN block.

Upvotes: 1

Pranav Wadhwa
Pranav Wadhwa

Reputation: 7736

There is no point of using if let value: Int?. If the if let works, then the value is an Int. There is no way that it could be nil. Therefore, you do not need to declare it as an optional.

Upvotes: 1

Related Questions