[swift-evolution] ternary operator ?: suggestion

Al Skipp al_skipp at fastmail.fm
Mon Dec 14 12:58:55 CST 2015


That’s a really interesting idea.
There’s potential to add parameter names. Ideally the second parameter name would be ‘else’, but that’s not really workable. 

func when<T>(fn: Bool, @autoclosure then: () -> T, @autoclosure or: () -> T) -> T {
  if fn { return then() }
  return or()
}

let x = when(true, then: 0, or: 1)

Nested version might be a bit scary though ; )

let nested = when(false, then: 0, or: when(false, then: 2, or: when(true, then: 3, or: 4)))

Al

> On 14 Dec 2015, at 18:38, David Owens II via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Thanks for the updated proposals; they are much easier to go through then the vast number of mails on this thread. I’ve tried to follow this thread as best as possible, so please forgive me if this has been addressed but I couldn’t find it.
> 
> Can you add to the proposal why a function cannot be added for tertiary expressions (under “Alternates Considered”):
> 
> func either<T>(@autoclosure fn: () -> Bool, @autoclosure _ left: () -> T, @autoclosure _ right: () -> T) -> T {
>     if fn() { return left() }
>     return right()
> }
> 
> let x = true ? 0 : 1
> 
> let y = either(true, 0, 1)
> 
> let f1: () -> Int = { print("f1"); return 0 }
> let f2: () -> Int = { print("f2"); return 2 }
> let z = either(true, f1(), f2())
> 
> let nested = either(false, 0, either(false, 2, either(true, 3, 4)))
> 
> This isn’t a full replacement for if-statements as expressions, but doesn’t it satisfy the tertiary requirements, at least in the most common of cases? The fallback is to use if-else if side-effects are something that is desired?
> 
> The name for the function could be better, but the point is to remove it from the parsing structure all together. Or is that something you find valuable?
> 
> -David

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


More information about the swift-evolution mailing list