Blog


Quickly creating a UITableViewCell

Aug 30, 2016
| UITableView
| Swift-3
| Operators

I don’t use Storyboards. This means I use dequeueReusableCell(withIdentifier:) instead of dequeueReusableCell(withIdentifier:for:) to be able to choose the UITableViewCellStyle.

The most standard method of doing this is the following (Swift 3, pretty much carried over from Objective-C):

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cellIdentifier = "reuseIdentifier"
  var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
  if (cell == nil) {
    cell = UITableViewCell(style: .value1, reuseIdentifier: cellIdentifier)
  }
  ...
  return cell!
}

In Swift this becomes annoying fast due to overuse of explicit unwrapping everywhere.

My personal solution to this is the following:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cellIdentifier = "reuseIdentifier"
  let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) ?? UITableViewCell(style: .value1, reuseIdentifier: cellIdentifier)

  ...

  return cell
}

This uses the nil coalescing operator to remove the if statement, only creates new cells when none can be dequeued, and guarantees a cell is created. No more forced unwrappings!

Hex Handling in Swift

Aug 9, 2016
| Welcome
| First
| Swift-2

This is my first time doing a blog in a long time (WordPress days).

I’ll probably post random things I come across while developing on iOS (Objective-C and Swift) and in Ruby on Rails.

Recent Discovery: Hex handling in Ints and Strings in Swift (Many thanks to Martin R on Stack Overflow)

String(16777215, radix: 16) // ffffff (aka 0xFFFFFF)

Int("ffffff", radix: 16) // 16777215