Swift:单个guard语句中的嵌套选项

时间:2017-06-12 16:40:48

标签: swift optional

我正在尝试保护从字符串到Float到Int的转换:

CREATE TABLE club_roster (
first_name VARCHAR(32),
last_name VARCHAR(32),
club VARCHAR(32)
);

swift 3编译器抱怨:

  

可选类型'Float?'的值没有打开;你的意思是用'!'还是'?'?

添加“?”但是没有帮助。并且“!”这里不对,不是吗?

是否可以解决这个问题,而不必使用两行或两个保护声明?

2 个答案:

答案 0 :(得分:7)

Optional has a map function made just for this:

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

答案 1 :(得分:4)

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)