Optional colon in ternary operator

I love the conciseness of the ternary operator to replace an 'if/then/else' construct. However, many times the 'else' part isn't needed. Why not make the colon an option?


        for item in items {
            if isTrue {
                thing.append(item)
            }
        }

            becomes this:
        for item in items {
            isTrue ? thing.append(item) : () // You have to add the colon and sort of a No-Op
        }

          better like this:
        for item in items {
            isTrue ? thing.append(item)
        }


This way if you don't add the colon then you have just an 'if/then' construct. I'm sure there must be some reason for this. Still, it would look cleaner.

Replies

In my opinion, the ternary operator is for use in expressions, and not when side-effects are the only purpose. In expressions, there must always be a result, and you are proposing an operator without a result.


If you write imperative code with the ternary operator, I would consider it obfuscated code, and I hope many with me wouldn't allow it to pass code review.


Also, the difference in conciseness between these two lines is minimal:


if isTrue { thing.append(item) }
isTrue ? thing.append(item)



The main reason that the ternary operator exists in the first place is that the C-style if statement doesn't return anything, not to make if statements shorter.

I understand what you're saying, but I don't understand the idea that 'if statements' shouldn't be any shorter. I kind of like getting rid of "brace forests" wherever I can. The thing is, the ternary operator can already replace 'if/then/else' for short one-line code, why not 'if/then' ?

Clearly you can write your code any way you’re comfortable with but the C idiom, which Swift inherits, is that:

  • if statements are used when you want a statement

  • ?: is a shortcut to avoid temporaries when you want a value

I realise that the example in your first post is just an example, but that specific case would be much better served by

filter(isIncluded:)
. For example, to find the even numbers in an array.
let a = [1, 2, 3, 4]
let b = a.filter { (i: Int) -> Bool in
    return i % 2 == 0
}
print(b)    // prints "[2, 4]"

If you really want to get concise you can crunch this down quite dramatically.

let b = a.filter { $0  % 2 == 0 }

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Yes, filter is what I used. It just surprised me that the ternary construct was 'if/then/else' only. I'm not a software engineer and I don't have a background in C programming so I'm sure I have a much shallower view of this than you guys. If that's the way the ternary operator is always going to be, then I'm fine with it. The universe probably won't explode or anything. :-)