4

I set a default string value with the ?? operator. But i get 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 behaviour

enter image description here

Unexpected behaviour

enter image description here

Godfather
  • 4,040
  • 6
  • 43
  • 70

2 Answers2

1

What version of Xcode do you use? I couldn't reproduce specified behaviour in Xcode 7 GM (7A218). If your version is lower it looks like a bug in previous beta.

enter image description here

Dmytro Hutsuliak
  • 1,741
  • 4
  • 21
  • 37
0

This is similar to Providing a default value for an Optional in Swift?

You can use a type annotation to force a non-optional value:

var message: String = JSON(result.value ?? "")["message"].string ?? "Default value"
Community
  • 1
  • 1
Tali
  • 861
  • 8
  • 17
  • But again the right side of the question should be evaluated to string not to optional string – Jason Nam Sep 15 '15 at 08:08
  • did you see my images? – Godfather Sep 15 '15 at 08:11
  • 2
    Of course you can, but I don't think that is what is wanted. `Using let optString: String? = nil var message = optString ?? "Default value"` also sets `message` to "Default value" with type `String`. The question is more like, why isn't it without optional, because the ?? operator does that in other contexts as well. – Binarian Sep 15 '15 at 08:12
  • I don't really see any good reason why the type defaults to `String?` here. My best explanation is that this is a bug in the language. – Tali Sep 15 '15 at 08:50
  • Or in the particular environment as it showed my test above. – Dmytro Hutsuliak Sep 15 '15 at 09:02