So because I got bored of having to manually nil-coalesce optional values, I decided to make the common default values into nice and easy-to-use extensions on Optional, as seen below:
public extension Optional {
var exists: Bool { return self != nil }
}
public extension Optional where Wrapped == String {
var orEmpty: Wrapped { return self ?? "" }
}
public extension Optional where Wrapped == Int {
var orZero: Wrapped { return self ?? 0 }
}
public extension Optional where Wrapped == Double {
var orZero: Wrapped { return self ?? 0 }
}
public extension Optional where Wrapped == Float {
var orZero: Wrapped { return self ?? 0 }
}
public extension Optional where Wrapped == Bool {
var orFalse: Wrapped { return self ?? false }
}
My issue arrives when attempting to use these on an optional value with a specific type.
I can call .orZero
on a variable of type String?
and get one of the following errors:
Ambiguous reference to member 'orZero'
'String?' is not convertible to 'Optional'
I'd like to know why Xcode is providing the .orZero
properties of such an optional as valid auto-completion options? I would've thought the generic constraints would prevent me from being able to see them.
For what it's worth, I'm using Xcode 10.1, and Swift 4.2