Brad
Brad

Reputation: 122

Concise Optional unwrapping

I am in the process of learning Swift, I have been experimenting with Optional unwrapping and came across this situation:

let displayText: String?

if let item = displayText {
    if let value = Double(item) {
        print("\(value)")
    } else {
        print("Didn't happen")
    }
} else {
    print("Didn't happen")
}

It seems something like this could be possible:

let displayText: String?

if let item = Double(displayText) {
    print("\(item)")
} else {
    print("Didn't happen")
}

In my case displayText might be nil, so force unwrapping is not what I want to do. I know I could hide this in a function to make it more concise, but I am really curious if there are other options.
Is there anyway to make this more concise?

Upvotes: 0

Views: 60

Answers (2)

Kametrixom
Kametrixom

Reputation: 14973

Another possibility is to use map on Optionals:

if let value = displayText.map({ Double($0) }) {
    print("\(value)")
}

Upvotes: 0

A few possibilities:

#1: The General. You can put multiple unwrapping variable declarations on one line.

if let item = displayText, value = Double(item) {
    print("\(value)")
}

#2: The Hack. In your specific case, you can also default the empty optional to something you know isn't going to be a valid string representation of a Double:

if let value = Double(item ?? "") {
    print("\(value)")
}

Upvotes: 2

Related Questions