[swift-evolution] Proposal: Replace ?? by an (optional) argument to ?
Greg Titus
greg at omnigroup.com
Sat Jan 30 12:07:48 CST 2016
> On Jan 30, 2016, at 9:27 AM, Amir Michail via swift-evolution <swift-evolution at swift.org> wrote:
> After thinking about it some more, it’s not really the position that is the problem.
>
> I think the problems with ?? are as follows:
>
> * not specialized to a boolean context (i.e, it is too general for most cases)
> * “??" is too catchy for something this minor
> * true/false contain too many letters for something this minor
I think you must be writing some (from my point of view) very unusual code indeed if most of the optional types you are dealing with are “Bool?”. If you are only dealing with optional booleans, then certainly, “??” would not be a very helpful construct.
In my experience ?? is most often used to conveniently end/resolve an optional chain with a default value, e.g.:
let x = array.first?.value ?? 0
as opposed to:
let x: Int
if let f = array.first {
x = f.value
} else {
x = 0
}
or perhaps:
let x: Int
if array.isEmpty {
x = 0
} else {
x = array[0].value
}
Optionals and optional-chaining are not rare (at least in my use of Swift), they are generally not in a boolean context, they are generally not minor, and “??” as an operator name is well suited to ‘resolving’ them with a default value.
It seems to me that if your list of items here is really your problem with “??”, then it seems as though you aren’t really using the operator as intended.
- Greg
> I would like to type something like this:
>
> if x?.isEmpty || nil { … }
> if x?.isNotEmpty && !nil { … }
>
> So one might consider turning “|| nil” into a suffix, say |nil.
> Similarly, one might consider turning “&& !nil” into a suffix, say &!nil.
>
> So maybe:
>
> if x?.isEmpty |nil { … }
> if x?.isNotEmpty &!nil { … }
>
>
>>
>> -Thorsten
>>
>>
>>>
>>>> -- E
>>>>
>>>>> On Jan 25, 2016, at 7:03 PM, Amir Michail via swift-evolution <swift-evolution at swift.org> wrote:
>>>>>
>>>>> Examples:
>>>>>
>>>>> * instead of x ?? false, you would have x?(false)
>>>>> * instead of x?.isEmpty ?? false, you would have x?(false).isEmpty
>>>>>
>>>>> I think this change would result in cleaner looking code.
>>>>>
>>>>>
>>>>> _______________________________________________
>>>>> swift-evolution mailing list
>>>>> swift-evolution at swift.org
>>>>> https://lists.swift.org/mailman/listinfo/swift-evolution
>>>>
>>>
>>> _______________________________________________
>>> swift-evolution mailing list
>>> swift-evolution at swift.org
>>> https://lists.swift.org/mailman/listinfo/swift-evolution
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
More information about the swift-evolution
mailing list