ternery operator in swift

The ternary operator in Swift is also called "conditional operator" and it's a shorthand for an if-else statement. The general syntax is as follows:

main.swift
(condition) ? (valueIfTrue) : (valueIfFalse)
45 chars
2 lines

Here's an example on how to use the ternary operator in Swift:

main.swift
let age = 18
let message = age >= 18 ? "You are an adult" : "You are not an adult"
print(message)
98 chars
4 lines

In the code above, we're using the ternary operator to check if age is greater than or equal to 18. If it is true, then the value of message will be "You are an adult". Otherwise, it will be "You are not an adult".

Note that although the ternary operator can make your code more concise, it can also make it harder to read, especially when used with complex expressions. Therefore, use it judiciously and only when it improves the readability of the code.

gistlibby LogSnag