Search code examples
if-statementswift3let

Swift 3: Set variable in if/else statement


I want to define a dynamic variable for my alert box. I'm getting a json from my server, like ok, error, username_in_use, etc etc.

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
)

But i'm getting this message:

Use of unresolved identifier 'error_msg'

How can I set a dynamic value for my alert title?

Thanks for help and sorry my poor english.


Solution

  • In your code, the scope of error_msg is limited to the blocks within the if statement. You could declare error_msg outside of the if blocks scope, e.g.

    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
    )