Search code examples
iosswiftoption-typeternary-operatorunwrap

Ternary Unwrapping in swift


In swift i'm using this code:

var categories: Results<Category>? //Realm dataType

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if let categories = categories, !categories.isEmpty {
        return categories.count
    } else {
        return 1
    }
}

I'm now looking to structure the code for my tableView as a ternary operator but don't know quite how to do this. I found the following page: https://dev.to/danielinoa_/ternary-unwrapping-in-swift-903 but it's still unclear to me.

What i tried is:

return categories?.isEmpty ?? {($0).count} | 1

or

let result = categories?.isEmpty ?? {($0).count} | 1
return result

but both giving errors. Any idea how I can solve this?


Solution

  • Instead of ternary you could use Optional.map to make it even simpler:

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return categories.map { $0.count } ?? 1
    }
    

    Or mixing Optional.map and ternary to achieve what you I think are trying to achieve:

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return categories.map { !$0.isEmpty ? $0.count : 1 } ?? 1
    }