Open Source projects from That Thing in Swift

PermissionScope

PermissionScope

Intelligent iOS permissions UI and unified API — 2,241⭐️ — GithubDocumentation

PermissionScope

Pantry

The missing light persistence layer for Swift — 433⭐️ — GithubDocumentation

Dequeueing Table Cells

Translating Objective-C to Swift code is not always hard


Hey! Listen! This article has changed significantly since it was originally posted about downcasting optionals returned from the iOS 6-era dequeueReusableCellWithIdentifier:. I’ve since changed it to contain the correct usage of dequeueReusableCellWithIdentifier:forIndexPath: which always returns a cell so that visitors know the correct code to use at first glance.


Dequeueing a table (or collection) cell is almost entirely UIKit API calls and they translate directly to Swift. Since iOS 7 we’ve been able to dequeue a guarenteed cell (no optionals or nil checks needed, thanks @olebegemann) as long as we have a prototype cell in the storyboard or have used one of registerClass:forCellWithReuseIdentifier: / registerNib:forCellWithReuseIdentifier:.

First, in Objective-C:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

	cell.textLabel.text = @"A cell";

	return cell;
}

Pretty simple, dequeue a reusable cell and customize it to your liking. Then return the cell as requested. The same thing in Swift:

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
	let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as UITableViewCell

	cell.textLabel.text = "A cell"

	return cell
}

This highlights a big point for people coming from Objective-C to Swift, and one I’ll restate often: the APIs haven’t changed (or have changed very little) and you can use them just about as you did before. Transitioning to Swift syntax is the hardest part, particularly mentally translating all those Objective-C methods you remember into their equivalents in Swift.

In this case, we don’t have to think much about the new constructs in Swift to get to the optimal code. Balancing between the approach that we used in Objective-C and more Swift-like approaches (see Filling Table Views) is an important part of our job as developers, particularly during these first few months of Swift.


Questions or comments? Find us on twitter or submit an issue on github

You'll get 1-2 emails per month