Last active
August 16, 2017 20:39
-
-
Save fmo91/13461af41521423833c5b8ec5fca31ba to your computer and use it in GitHub Desktop.
Protocol extension to help using UITableView protocols in a better way.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol ReusableViewEnum {} | |
extension ReusableViewEnum where Self: RawRepresentable, Self.RawValue == Int { | |
static var all: [Self] { | |
var index = 0 | |
var allItems = [Self]() | |
while let item = Self(rawValue: index) { | |
allItems.append(item) | |
index += 1 | |
} | |
return allItems | |
} | |
static func build(with value: Int) -> Self { | |
guard let row = Self(rawValue: value) else { | |
fatalError("Unimplemented value: \(value)") | |
} | |
return row | |
} | |
} | |
// --------------------- | |
// EXAMPLE USAGE CODE: | |
// You only have to define the enum | |
fileprivate enum ProfileSections: Int, ReusableViewEnum { | |
case picture = 0 | |
case name | |
case email | |
case password | |
} | |
// And use it in your code: | |
func numberOfSections(in tableView: UITableView) -> Int { | |
return ProfileSections.all.count | |
} | |
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
switch ProfileSection.build(with: section) { | |
case .picture : return 1 | |
case .name : return 1 | |
case .email : return 1 | |
case .password : return 1 | |
} | |
} | |
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
switch ProfileSection.build(with: indexPath.section) { | |
case .picture : // Dequeue profile picture section | |
case .name : // Dequeue name section | |
case .email : // Dequeue email section | |
case .password : // Dequeue password section | |
} | |
} | |
// Please note we are not using default clause, because it's an exhaustive switch. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment