randombits
randombits

Reputation: 48450

Correct way to unwrap an Optional Integer in Swift 3

What is the correct way to set fullLength here?

var index = foo.index(foo.startIndex, offsetBy: SOME_NUM)
let length = Int(foo.substring(to: index))

if let fullLength = length? + SOME_NUM {
  return
}

The problem here is length? is an Optional. I had this working with:

fullLength = length! + SOME_NUM, but I don't want to risk using ! in the event length is nil.

Upvotes: 2

Views: 3296

Answers (4)

rahul verma
rahul verma

Reputation: 39

You can make use of nil-Coalescing operator.To help you with understanding nil-Coalescing operator let us take an example, which will solve your problem too.The nil-coalescing operator '??' in a ?? b unwraps an optional a if it contains a value or returns a default type b if a is nil. It is shorthand for

    a != nil ? a! : b

Now coming to your question

    var index = foo.index(foo.startIndex, offsetBy: SOME_NUM)
    let length = Int(foo.substring(to: index))
    let someDefaultValue = 0 

    let fullLength = length ?? someDefaultValue + SOME_NUM
    // or to be precise , you can also 
    //replace someDefaultValue with 0 in above code

Upvotes: 2

Jake
Jake

Reputation: 13753

I would do this:

let index = foo.index(foo.startIndex, offsetBy: SOME_NUM)

guard let length = Int(foo.substring(to: index)) else {
    //show error
    //return reasonable value for error
}

let fullLength = length + SOME_NUM

This way approaches the problem as length being a valid number (not nil) as a precondition of the execution of the rest of the code.

Upvotes: 1

Keiwan
Keiwan

Reputation: 8251

You could rewrite it as

if let length = length {
    let fullLength = length + SOME_NUM
}

Upvotes: 2

ghostatron
ghostatron

Reputation: 2650

if let length = length
{
    fullLength = length + SOME_NUM
}

Upvotes: 1

Related Questions