Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous use of "??"

Tags:

swift

I have a couple of lines of working code:

    let email = User.sharedInstance.emailAddress ?? ""
    accountEmailAddress.text = email

User.sharedInstance is a non-optional instance of the User class. Its emailAddress property is an optional String?. accountEmailAddress is a UILabel.

If I try to turn this into a single line of code:

    accountEmailAddress.text = User.sharedInstance.emailAddress ?? ""

I get the Swift compiler error "Ambiguous use of '??'".

I can't quite figure out what's ambiguous about the use of the nil coalescing operator here. I'm looking to find out why the compiler's complaining, and, out of curiosity, if there's a way of making this a clean one-liner.

(Xcode 6 beta 6.)

Edit: Minimal reproduction in a playground:

// Playground - noun: a place where people can play
var foo: String?
var test: String?

// "Ambiguous use of '??'"
foo = test ?? "ValueIfNil"
like image 936
Matt Gibson Avatar asked Sep 02 '14 09:09

Matt Gibson


1 Answers

I guess this is because of the optionality of UILabel.text. Operator ?? has 2 overloads – one returns T and the other returns T?.

Since UILabel.text accepts both String and String?, compiler cannot decide which overload to use, thus throwing an error.

You can fix this error by strictly specifying the result type:

String(User.sharedInstance.emailAddress ?? "")

(User.sharedInstance.emailAddress ?? "") as String

// or, when String! will become String? in the next beta/gm

(User.sharedInstance.emailAddress ?? "") as String?

Nevertheless, the compiler should automatically prefer non-optional types in this kind of situations, so I suggest filing a bug report on this.

like image 192
akashivskyy Avatar answered Nov 03 '22 20:11

akashivskyy