Reputation: 502
Is it a good idea to use inline if statements on optional values when not changing the value itself: -
var optionalValue:[Int]?
var isOptionalValueCount = 0
optionalValue = [4, 5, 6]
if let value = optionalValue {
isOptionalValueCount = value.count
}
println("amount of integers (using usual syntax): \(isOptionalValueCount)")
// "amount of integers (using usual syntax): 3"
isOptionalValueCount = optionalValue != nil ? optionalValue!.count : 0
println("amount of integers (using inline): \(isOptionalValueCount)")
// "amount of integers (using inline): 3"
This makes the code more succinct, however we still have the "!" when calculating the optionalValue.count- to me this seems like a bad code smell.
What are the disadvantages of using the inline if statement to deal with optionals like this?
Upvotes: 3
Views: 746
Reputation: 72750
I don't see any disadvantage, beside not looking good in my opinion, so I'd prefer the optional binding. However I think you can rewrite that as:
isOptionalValueCount = optionalValue?.count ?? 0
If optionalValue
is nil
, then the left expression evaluates to nil
, and the nil coalescing operator returns the expression at right.
Upvotes: 3