Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/109.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios swift中用于错误处理的Guard语句_Ios_Swift - Fatal编程技术网

Ios swift中用于错误处理的Guard语句

Ios swift中用于错误处理的Guard语句,ios,swift,Ios,Swift,我试着运行下面的语句,但代码中跳过了它 guard let num1 = num1Input.text else { show("No input in first box") return } 有人能告诉我为什么文本字段为空时此语句没有运行吗?您应该检查文本的长度,而不是检查其nil,即: guard num1Input.text.characters.count > 0 else { ... } 如果文本是可选的,您可以这样做 guard let num1 =

我试着运行下面的语句,但代码中跳过了它

guard let num1 = num1Input.text else
{
    show("No input in first box")
    return
}

有人能告诉我为什么文本字段为空时此语句没有运行吗?

您应该检查文本的长度,而不是检查其
nil
,即:

guard num1Input.text.characters.count > 0 else {
  ...
}
如果文本是可选的,您可以这样做

guard let num1 = num1Input.text where num1.characters.count > 0 else {
  ...
}

此语句正在测试
文本是否为
nil
,但您可能需要测试字符串是否为空,因此

guard let input = num1Input.text where input.characters.count > 0 else {
    print("empty")
    return
}
或者干脆

guard num1Input.text?.characters.count > 0 else {
    print("empty")
    return
}

您可以使用
where
子句检查非nil非空

guard let num1 = num1Input.text where !num1.isEmpty else {
    show("No input in first box")
    return
}

请使用
.isEmpty
请使用
.isEmpty
请。