ios 在 Swift 中 if let 赋值中 where 的使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38762513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:50:48  来源:igfitidea点击:

Usage of where in if let assignment in Swift

iosswiftwhereoptionalswift3

提问by Fabrizio Bartolomucci

The Swift documentation at page 61 of the Swift manual hints to the possibility of using whereto join an optional binding with a regular condition. Yet when I do it I have a warning suggesting me to substitute the wherewith a comma like in the following piece of code:

Swift 手册第 61 页的 Swift 文档提示了使用where常规条件连接可选绑定的可能性。然而,当我这样做时,我有一个警告,建议我where用逗号替换,如下面的代码所示:

if let geocodingError = error as? NSError where geocodingError.code == 2

采纳答案by Alex

Example with two conditions

具有两个条件的示例

if let x = y, let a = b, a == x && !x.isEmpty {

回答by Grimxn

In Swift 3 this syntax has changed.

在 Swift 3 中,此语法已更改。

What was

什么是

if let x = y, a = b where a == x {

if let x = y, a = b where a == x {

Is now

就是现在

if let x = y, let a = b, a == x {

if let x = y, let a = b, a == x {

The justification is that each sub-clause of the if ... {is now an independent boolean test.

理由是每个子条款if ... {现在都是一个独立的布尔测试。

See the Xcode Release notes& the Swift Evolution proposalfor more info about this change.

有关此更改的更多信息,请参阅 Xcode发行说明Swift Evolution 提案

回答by luhuiya

In xcode 9

在 xcode 9

if let str = textField.text as String!, !str.isEmpty
{
   params[key] = str
   TextFieldHelper.setup(textField: textField)
}
else
{ 
   TextFieldHelper.error(textField: textField)
}