Swift 3:在if/else语句中设置变量

Swift 3: Set variable in if/else statement

我想为我的警告框定义一个动态变量。我从我的服务器得到一个 json,比如 ok,error,username_in_use,等等

let response = parseJSON["message"] as? String

if response == "username_in_use" {
    let error_msg = "Username in already use!"
} else if response == "email_in_use" {
    let error_msg = "Email address in already use!"
} else {
    let error_msg = "Unknown Error!"
}

alertView.showTitle(
    alertTitle: error_msg
)

但我收到了这条消息:

Use of unresolved identifier 'error_msg'

如何为提醒标题设置动态值?

感谢您的帮助,抱歉我的英语不好。

您应该在 if 语句之外声明 let error_msg,以便在将其传递给警报时可见。

   let response = parseJSON["message"] as? String

   var error_msg = ""

   if response == "username_in_use" {
       error_msg = "Username in already use!"
   } else if response == "email_in_use" {
       error_msg = "Email address in already use!"
   } else {
       error_msg = "Unknown Error!"
   }

   alertView.showTitle(alertTitle: error_msg)

在您的代码中,error_msg 的范围仅限于 if 语句中的块。 您可以在 if 块范围之外声明 error_msg,例如

let response = parseJSON["message"] as? String
var error_msg:String

if response == "username_in_use" {
    error_msg = "Username in already use!"
} else if response == "email_in_use" {
    error_msg = "Email address in already use!"
} else {
    error_msg = "Unknown Error!"
}

alertView.showTitle(
    alertTitle: error_msg
)

这是 switch 语句的完美用例:

let errorMsg: String

switch response {
case "username_in_use": errorMsg = "Username in already use!"
case "email_in_use": errorMsg = "Email address in already use!"
default: errorMsg = "Unknown Error!"
}

如果只想使用parseJSON字典中键"message"对应的可能存在的(Any?)值直接进一步processing/translation,则需要' 必须存储此值,但可以内联使用它以继续将其处理为有效的错误消息。例如,使用 switch 语句:

var error_msg: String = "Unknown error"
switch parseJSON["message"] {
    case let val as String where val == "username_in_use": error_msg = "Username in already use!"
    case let val as String where val == "email_in_use": error_msg = "Email address in already use!"
    case _: ()
}

// ...
alertView.showTitle(
    alertTitle: error_msg
)

或者,使用辅助字典将 JSON "message" 代码(值)映射到错误消息,轻松允许使用 nil 合并运算符来提供默认(未知错误)消息:

let error_msgs = [
    "username_in_use" : "Username in already use!",
    "email_in_use"    : "Email address in already use!"]

let error_msg = error_msgs[parseJSON["message"] as? String ?? ""] ?? "Unknown Error!"

// ...
alertView.showTitle(
    alertTitle: error_msg
)