Swift macOS应用程序中的表单验证问题

Swift macOS应用程序中的表单验证问题,swift,macos,cocoa,swift3,Swift,Macos,Cocoa,Swift3,我正在尝试运行设置表单,确保用户没有将任何必填字段留空 一些表单字段是安全的(例如密码) 循环检查所有这些字段并检查它们是否为空最简单的方法是什么 我尝试了以下方法-但我遇到了一个奇怪的错误: if textfield1.stringValue == "", textfield2.stringValue == "", passwordfield.stringValue == "" { //Shows error: Braced block of statemen

我正在尝试运行设置表单,确保用户没有将任何必填字段留空

一些表单字段是安全的(例如密码)

循环检查所有这些字段并检查它们是否为空最简单的方法是什么

我尝试了以下方法-但我遇到了一个奇怪的错误:

if textfield1.stringValue == "", 
    textfield2.stringValue == "",
    passwordfield.stringValue == "" {
        //Shows error: Braced block of statements is an unused closure
}

此外,我无法将所有这些NSTextfields分组到一个数组中,因为密码textfields是NSSecureTextField,尽管从NSTextfield继承,但不能与NSTextfield一起分组。

在Swift 2下,Eric Aya正确识别了以下内容:

    if textfield1.stringValue == "" && textfield2.stringValue == "" &&  == "" {

    }
它也在Swift 3下编译


另一方面,您在问题中输入的代码实际上在Swift 3中有效。

在Swift 2下,Eric Aya正确识别了以下内容:

    if textfield1.stringValue == "" && textfield2.stringValue == "" &&  == "" {

    }
它也在Swift 3下编译


另一方面,您在问题中输入的代码实际上在Swift 3中起作用。

另一种方法是使用string对象的isEmpty变量检查空字符串

let userName = ""
let email = ""

if(userName.isEmpty && email.isEmpty) {
    print("empty strings")
}
else {
    print("good strings")
}

使用string对象的isEmpty变量检查空字符串的另一种方法

let userName = ""
let email = ""

if(userName.isEmpty && email.isEmpty) {
    print("empty strings")
}
else {
    print("good strings")
}
您可以将
NSTextField
NSSecureTextField
放在同一个数组中。这确实是一种找到空的方法

let tf = NSTextField()
let stf = NSSecureTextField()
let tf2 = NSTextField()
tf2.stringValue = "some text"

let all = [tf, stf, tf2]

let emptyTextFields = all.filter { $0.stringValue.isEmpty }
此外,在您的示例中,您不能使用逗号对
中的条件进行分组。如果
,则必须使用
&&

if tf.stringValue.isEmpty && stf.stringValue.isEmpty && tf2.stringValue.isEmpty {
    // do something
}
但这不是一个好的解决方案,最好使用数组和筛选器。

您可以在同一数组中使用
NSTextField
NSSecureTextField
。这确实是一种找到空的方法

let tf = NSTextField()
let stf = NSSecureTextField()
let tf2 = NSTextField()
tf2.stringValue = "some text"

let all = [tf, stf, tf2]

let emptyTextFields = all.filter { $0.stringValue.isEmpty }
此外,在您的示例中,您不能使用逗号对
中的条件进行分组。如果
,则必须使用
&&

if tf.stringValue.isEmpty && stf.stringValue.isEmpty && tf2.stringValue.isEmpty {
    // do something
}
但这不是一个好的解决方案,最好使用数组和过滤器