[Swift] Support shorthand ternary operator
| Originator: | martijn | ||
| Number: | rdar://17273004 | Date Originated: | 6/11/2014 |
| Status: | Open | Resolved: | |
| Product: | Developer Tools | Product Version: | |
| Classification: | Reproducible: |
Some languages, including GNU C, support a shorthand version of the ternary operator (?:) where the second operand is optional. This implicitly uses the first operand as the second operand also. It is often used when a check is required before returning a value, returning a default value instead when the check fails.
In Swift, optional chaining is one use case where this seems especially useful. For example, currently you need to repeat the chain in the second operand and remember to unwrap the resulting value:
override func intrinsicContentSize() -> CGSize {
return user.image ? user.image!.size : CGSize(width: 100, height: 100)
}
Supporting a shorthand ternary operator would simplify this code:
override func intrinsicContentSize() -> CGSize {
return user.image?.size ?: CGSize(width: 100, height: 100)
}
It might also be more efficient, as the chain only needs to be traversed once, making it functionally similar to:
override func intrinsicContentSize() -> CGSize {
if let size = user.image?.size {
return size
} else {
return CGSize(width: 100, height: 100)
}
}
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!