Introduction
Let's say you have a static table view, where each cell needs a different treatment. One way to differentiate them is by assigning a type to the model so you can use a switch
later. The problem is that initializing an enum for this Type
later causes warnings in Xcode and doesn't compile.
In my project, I have a table with Album settings. This table has a few sections, one of this sections is "sharing".
Here we have 3 rows. We need to detect taps in the first and third row, taps in the second row are ignored. We need to detect toggle switching in the second row.
These are static cells, so we could use indexPath comparison to see if they are the first, the second or the third. But comparing to indexes can be difficult to read, that's why we have an enum to differentiate which type of row they are.
struct ShareSettingRow {
enum `Type`: Int {
case copySharingURL
case anyoneCanAddPhotos
case unshare
var title: String {
switch self {
case .copySharingURL: return NSLocalizedString("Copy sharing URL", comment: "")
case .anyoneCanAddPhotos: return NSLocalizedString("Anyone can add photos", comment: "")
case .unshare: return NSLocalizedString("Unshare album", comment: "")
}
}
}
}
These cells use the class AlbumSettingCell
. Here's how we style them.
func update(albumSection: AlbumSettingsSection, album: Album, indexPath: IndexPath) {
let sectionKind = albumSection.kind
self.textLabel?.textColor = UIColor(hex: "6A6970")
self.textLabel?.font = .light(16)
self.detailTextLabel?.text = nil
self.accessoryView = nil
switch sectionKind {
// ... more sections
case .sharing:
let sharingRowKind = ShareSettingRow.`Type`(rawValue: indexPath.row)!
switch sharingRowKind {
case .copySharingURL:
self.textLabel?.textColor = UIColor(hex: "CC6EF1")
self.textLabel?.font = .regular(16)
self.accessoryView = UIImageView(image: UIImage(named: "get-link-gray")!)
case .anyoneCanAddPhotos:
self.accessoryView = self.switch
break
case .unshare:
self.textLabel?.textColor = UIColor(hex: "EF3138")
self.textLabel?.font = .regular(16)
}
self.textLabel?.text = sharingRowKind.title
//... more sections
}
}
Problem
Swift doesn't let you do this:
let sharingRowKind = ShareSettingRow.`Type`(rawValue: indexPath.row)!
Proposed solutions
Use Kind
Use Kind instead of Type
for this cases since it's not a reserved word.
Use models
Create a struct for each row and assign a type to them.