[swift-evolution] Nil-rejection operator

Hooman Mehr hooman at mac.com
Thu Feb 9 13:08:48 CST 2017


I think the best solution is overloading the existing ?? operator. It is very easy to do:

func ??<T,U: Error>(lhs: T?, rhs: U) throws -> T {
    
    if let lhs = lhs { return lhs } else { throw rhs }
}

then you can say:

do {
    
    let y = try x ?? myError
    
} catch ...

It might even make sense to add to the standard library.

> On Feb 9, 2017, at 12:04 AM, Jack Newcombe via swift-evolution <swift-evolution at swift.org> wrote:
> 
> This can actually be accomplished now using a closure:
> 
> 	let value = optionalValue ?? { throw CustomError.failure }()
> 
> However, this adds a layer of indirection that I’m not keen on and lacks the readability and maintainability of a well-defined operator.
> 
> The problem with changing the nil-coalescing operator is that it means allowing the second operand to be a statement rather than an expression, which I assume would be seen as an unacceptable.
> 
>> On 9 Feb 2017, at 07:56, Brent Royal-Gordon <brent at architechies.com> wrote:
>> 
>>> On Feb 8, 2017, at 12:00 PM, Jack Newcombe via swift-evolution <swift-evolution at swift.org> wrote:
>>> 
>>> I propose the introduction of a nil-rejection operator (represented here as !!) as a complement to the above operators.
>>> .
>>> This operator should allow an equivalent behaviour to the forced unwrapping of a variable, but with the provision of an error to throw in place of throwing a fatal error.
>>> 
>>> - value !! Error :
>>> 	if value is nil, throw non-fatal error
>>> 	if value is not nil, return value
>>> 
>>> Example of how this syntax might work (Where CustomError: Error):
>>> 
>>> 	let value = try optionalValue !! CustomError.failure
>> 
>> Rather than invent a new operator, I'd prefer to make `throw` an expression rather than a statement. Then you could write:
>> 
>> 	let value = optionalValue ?? throw CustomError.Failure
>> 
>> One issue here would be figuring out the proper return type for `throw`. Although if `Never` were a subtype-of-all-types, that would of course work. :^)
>> 
>> -- 
>> Brent Royal-Gordon
>> Architechies
>> 
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170209/b516d4b4/attachment.html>


More information about the swift-evolution mailing list