[swift-evolution] ternary operator ?: suggestion

Brent Royal-Gordon brent at architechies.com
Thu Dec 17 01:09:12 CST 2015


> My reason for suggesting the change is that it would be nice to have a one liner for non-boolean values. Especially when the mapping isn't likely to be reused anyplace else. I run into this a fair amount, and the inline way I do it (via a Dict) requires a lot of verbosity (keys are likely to be Enums and need to be explicitly declared for the Dict).

You can improve the ergonomics of this with a custom operator:

	infix operator ??? {}		// Used because ? is reserved; in practice, you should use something else.
	
	func ???<Key, Value>(key: Key, dictionary: [Key: Value]) -> Value {
	    return dictionary[key]!
	}
	
	let alignment = NSTextAlignment.Left
	alignment ??? [.Left: "Left", .Right: "Right", .Center: "Center", .Justified: "Justified"]

Actually, this *almost* does what you want. No @autoclosure for the values and no exhaustiveness checking, but otherwise...

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list