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

时间:2016-12-11 17:34:07

标签: if-statement swift3 let

我想为警报框定义一个动态变量。我从我的服务器上获取了一个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'

如何为警报标题设置动态值?

感谢您的帮助,对不起我的英语很差。

4 个答案:

答案 0 :(得分:2)

这是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!"
}

答案 1 :(得分:1)

在您的代码中,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
)

答案 2 :(得分:1)

如果您只想使用Any词典中与键"message"对应的可能存在的parseJSON?)值进行直接进一步处理/翻译,则无需存储此值,但可以使用内联继续将其处理为有效的错误消息。例如,使用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
)

答案 3 :(得分:0)

您应该在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)