Sean
Sean

Reputation: 721

Working with optionals elegantly

I have a property in a class returning the total / count. Both total and count are optionals. Is there a more elegant way of checking that they have values than this:

var equalAmount: Float? { 
    if total != nil, count != nil {
        return total! / Float(count!)
    } else {
        return nil
    }
}

Upvotes: 2

Views: 88

Answers (4)

Bigbearlazier
Bigbearlazier

Reputation: 1

Use Ternary Conditional Operator:

var equalAmount: Float? { 
    return total != nil && count != nil ? total! / Float(count!) : nil
}

Documentation: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html

Upvotes: 0

Charles Srstka
Charles Srstka

Reputation: 17060

Just about any way is more elegant than using force-unwrap. Take your pick between:

if let: closest to your current design

if let total = total, let count = count {
    return total / Float(count)
} else {
    return nil
}

guard let: less indentation

guard let total = total, let count = count else { return nil }
return total / Float(count)

or map and flatMap: for a one-liner

return total.flatMap { total in count.map { total / Float($0) } }

Upvotes: 4

cpt. Sparrow
cpt. Sparrow

Reputation: 415

Use guard let to unwrap the values if the condition in the guard is not true then the else part will return to the function and this will not execute the other in it. guard is more preferable in compare to if let statements to check the unwrap values and to return immediately :

var equalAmount: Float? { 
    guard let newTotal = total else {
         return nil
    }
    guard let newCount = count else {
         return nil
    }

return newTotal/newCount

}

Upvotes: 0

J. Doe
J. Doe

Reputation: 13123

var equalAmount: Float? { 
    guard let totalUnwrapped = total,
          let countUnwrapped = count
          else {return nil}
    return totalUnwrapped / countUnwrapped
}

This would be my approach. I use guard let when you really need the variables to continue the function.

Upvotes: 2

Related Questions