Swift: Nested optionals in a single guard statemen

2019-07-04 00:23发布

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?

2条回答
手持菜刀,她持情操
2楼-- · 2019-07-04 01:03

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)

查看更多
仙女界的扛把子
3楼-- · 2019-07-04 01:10

Optional has a map function made just for this:

guard let v = Float("x").map(Int.init) else {
    return nil
}
查看更多
登录 后发表回答