I can not display the following expression through ternary operators. Can someone tell me?

let child = 0 let teenager = 12 let youth = 16 let adult = 25 let mature = 40 let elderly = 55 let aged = 75 let anton = 31 var age: String if anton > aged { age = "is aged" } else { if anton > elderly { age = "is elderly" } else { if anton > mature { age = "is mature" } else { if anton > adult { age = "is adult" } else { if anton > youth { age = "is youth" } else { if anton > teenager { age = "is a teenager" } else { if anton > child { age = "is a child" } else { age = "was never born" } } } } } } } print("Anton \(age)") 
  • Do not complicate - just use switch - case - Kromster

2 answers 2

I don't know why you need it

 let child = 0 let teenager = 12 let youth = 16 let adult = 25 let mature = 40 let elderly = 55 let aged = 75 let anton = 31 var age: String age = (anton > aged ? "aged" : (anton > elderly ? "is elderly" : (anton > mature ? "is mature" : (anton > adult ? "is adult" : (anton > youth ? "is youth" : (anton > teenager ? "is a teenager" : (anton > child ? "is a child" : "was never born"))))))) print("Anton \(age)") 

    You should never do so many nested if - else , such code is not possible to read. switch - case also not a very convenient option. I propose such a solution, create a dictionary, where the number is the key and the text is the value. Next, create a cycle and go through each key and compare it with the value you need, as soon as the key is greater than the value, then output the text with the given key.

     var dictionary = [0 : "is a child", 12 : "is a teenager", 16 : "is youth", 25 : "is adult", 40 : "is mature", 55 : "is elderly", 75 : "is aged"] var age: String = "was never born" let anton = 31 var temp = 0 for (key, value) in dictionary { if anton > key && key > temp { age = value temp = key } } print("anton \(age)") 

    Pay attention to the variable var temp = 0 , it was created in order to save the maximum age that was found in the dictionary, since the dictionary does not guarantee you the order of the elements, unlike the array, you can not just go through the dictionary and find that value which will be more than anton . Once in the loop we found an item that is larger than anton , save the value in temp and go further in the dictionary, looking for an item that is larger than anton And more than temp .