[swift-evolution] [Pitch] Use "where" in combination with "??" to provide Ternary-like functionality

Brent Royal-Gordon brent at architechies.com
Tue May 24 00:23:17 CDT 2016


> Earlier e-mail example:
>>     let foo = 
>>         "positive" where ( bar > 0 )  ?? 
>>         "negative" where ( bar < 0 ) ?? 
>>         "zero"
> 
> let foo = bar > 0 ? "positive" :
>           bar < 0 ? "negative" :
>           "zero"

See, this just makes me want to remix ternary...

	let foo = 	(bar > 0) :: "positive" ??
			(bar < 0) :: "negative" ??
			"zero"

	// :: is not actually legal to declare, but notionally...
	infix operator :: {
		associativity left
		precedence 133
	}
	func :: <B: BooleanType, T>(lhs: B, rhs: @autoclosure () -> T?) -> T? {
		guard lhs else {
			return nil
		}
		return rhs()
	}

`::` is an operator which evaluates the condition on the left and returns the right if true, or nil otherwise. You can chain `::`s together with the existing `??` operator. You can terminate the sequence with a trailing `?? value` to ensure you won't get a nil. Or you can leave off the trailing `??`, or even omit the chain of `??`s altogether if `::` by itself does what your code needs.

Actually, the main problem I see here is that `??`'s, and therefore `::`'s, precedence is too tight—it binds more tightly than the comparison operators. One solution might be to put `::` and `??` at their current high precedence, but also have `:` and `?` with the same semantics at a precedence level just above assignment...

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list