Can you use built-in if statements with optional values?

Is it a good idea to use inline if statements on optional values ​​without 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 concise, but we still have the "!" when calculating the Value.count- option it seems like a bad code smell to me.

What are the disadvantages of using an inline if statement to handle options like this?

+3


source to share


1 answer


I see no downside other than not looking good in my opinion, so I would prefer the optional binding. However, I think you can rewrite this as:

isOptionalValueCount = optionalValue?.count ?? 0

      



If optionalValue

- nil

, then the left expression evaluates to nil

, and the nil union operator returns the expression on the right.

+3


source







All Articles