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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With