问题
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