Swift: Nested optionals in a single guard statement

感情迁移 提交于 2019-12-13 13:43:02

问题


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?


回答1:


Optional has a map function made just for this:

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



回答2:


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)



来源:https://stackoverflow.com/questions/44504563/swift-nested-optionals-in-a-single-guard-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!