Swift:在单个警卫声明中嵌套了可选内容 [英] Swift: Nested optionals in a single guard statement

查看:57
本文介绍了Swift:在单个警卫声明中嵌套了可选内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图保护从字符串到Float到Int的转换:

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

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

迅速的3编译器抱怨:

可选类型浮点型"的

值?没有包装;你的意思是使用'!'还是?"?

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?

推荐答案

Optional具有 map 函数就是为此而设计的:

Optional has a map function made just for this:

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

这篇关于Swift:在单个警卫声明中嵌套了可选内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆