The default value of optional swift does not make it nonOptional

I set the default string value using the operator. But am I getting an optional string?

    request(.GET, CUSTOMER_URL, parameters: params, encoding: .URL).responseJSON { (request, response, result) -> Void in
        var message = JSON(result.value ?? "")["message"].string ?? "Default value to make it nonOptional"
        switch(result) {
        case .Success(let json):
            if let customer = JSON(json)["customer"].dictionaryObject {
                GlobalCache.sharedInstance.setCustomer(customer)
            }
            completion(succeed: response?.statusCode == 200, message: message)
        case .Failure(_,_):
            completion(succeed: false, message: message)
        }
    }

message is String?

Expected Behavior

enter image description here

Unexpected behavior

enter image description here

+4
source share
2 answers

What version of Xcode are you using? I could not reproduce the specified behavior in Xcode 7 GM (7A218). If your version is lower, it looks like an error in the previous beta.

enter image description here

+1
source

Is it like Providing a default value for an Option parameter in Swift?

You can use type annotation to force an optional value:

var message: String = JSON(result.value ?? "")["message"].string ?? "Default value"
0
source

Source: https://habr.com/ru/post/1607407/


All Articles