Thomas Tempelmann
Thomas Tempelmann

Reputation: 12053

Swift: Nested optionals in a single guard statement

I am trying to guard a conversion from string to Float to Int:

guard let v = Int (Float("x")) else {
    return -1
}

The swift 3 compiler complains:

value of optional type 'Float?' not unwrapped; did you mean to use '!' or '?'?

Adding "?" does not help, though. And "!" would be wrong here, wouldn't it?

Is it possible to solve this, without having to use two lines or two guard statements?

Upvotes: 3

Views: 2684

Answers (2)

vacawama
vacawama

Reputation: 154593

You can do it with one guard statement with an intermediate variable:

guard let f = Float("x"), case let v = Int(f) else {
    return
}

Note: The case is there as a workaround for the fact that Int(f) does not return an optional value. (Thanks for the idea, @Hamish)

Upvotes: 5

Alexander
Alexander

Reputation: 63272

Optional has a map function made just for this:

guard let v = Float("x").map(Int.init) else {
    return nil
}

Upvotes: 7

Related Questions