Swift - WhaleTalk - Additional Challenges - ternary operator

I don’t know how to read this line of the solution :
case “e”, “u”:
** // Used a ternary operator to determine which letters get added**
** output += lowerChar == “e” ? “EE” : “UU”**
For me this is not logical, output = output + lowercase == “e” why is that, output isn’t empty it already has some letters in memory, so output + lowercase can’t be == “e” , please what is wrong with my interpretation ?

the copy paste of the code:
var input = “I know not all that may be coming, but be it what it will, I’ll go to it laughing. -Moby ■■■■”
var output = “”
for char in input {
let lowerChar = char.lowercased()

switch lowerChar {
case “a”, “i”, “o”:
output += lowerChar.uppercased()
// Both “e” and “u” are in a single case
case “e”, “u”:
// Used a ternary operator to determine which letters get added
output += lowerChar == “e” ? “EE” : “UU”

Hi, @zerg38,

Excellent question. The "e", "u" case code that increments output is not checking whether output + lowerChar == "e" as it appears. The ternary operator is actually shorthand for an if-else statement. That if-else statement tells our case statement which value should be tacked on to the end of output.

Essentially, it is saying:

if lowerChar == "e" {
    output += "EE"
} else {
    output += "UU"

it might help to think of it as this when you are reading it:
output += (if lowerChar == "e" then "EE" else "UU")

That being said, I personally don’t use ternary operators often because I typically value readability of code over how short the code is, and for me it’s quicker and easier to read and debug code when it’s fully written out. I really only use this sort of syntax when it makes sense for it to fit on one line (think list comprehension in Python).

1 Like

I understand now :smiley:, thanks also for the advice about readability.

1 Like

No problem. Happy coding!


This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.