Use conditional operators (aka ternary operators) to make your code more legible and clear. Conditional assignment is the most common use case for ternary operators.
With the ternary operator, you can turn this:
1 2 3 4 5 6 7
Only one line of code, and a lot easier to read and understand when you’re familiar with the syntax.
The basic syntax for using the ternary operator is:
As you can see, ternary operator checks the condition and returns one of the values based on the result.
In some cases, you can even omit the true side of operation. Consider the following statement:
Here, we check to see if our user has uploaded a profile photo. If that’s the case,
self.uploadedPhoto is non-nil and will evaluate to TRUE. Consequently,
self.uploadedPhoto will be returned and assigned to profilePhoto. However if no photo has been uploaded,
self.uploadedPhoto will be nil and will evaluate to FALSE. Therefore, defaultPhoto will be assigned to profilePhoto.
The above statement can be rewritten like this:
Again, if self.uploadedPhoto is non-nil, it will be assigned to profilePhoto, otherwise, defaultPhoto will.