In our last post, we learned how to create and use a Generic Protocol by using the associated type. In this post, we will create a generic protocol for UITableView data source. You can use it for any UIViewController which has UITableView and follows the MVVM design pattern.
protocol TableListProtocol: AnyObject {
associatedtype Item
var numberOfSections: Int { get }
func numberOfItems(in section: Int) -> Int
func itemFor(index: Int,
section: Int) -> Item?
func heightFor(index: Int,
section: Int) -> CGFloat
func heightForHeder(in section: Int) -> CGFloat
func heightForFooter(in section: Int) -> CGFloat
}
//Optional
extension TableListProtocol {
func heightForHeder(in section: Int) -> CGFloat {
return 0
}
func heightForFooter(in section: Int) -> CGFloat {
return 0
}
}
How to use it?
Suppose you have a Home Screen and in it you want to present a list view.
We are using an MVVM design pattern so we will have a HomeViewModel class. In HomeViewModel, we will write all the business logic for the Home Screen.
Here is the example using TableListProtocol
protocol HomeProtocol: AnyObject, TableListProtocol {
var layout: HomeLayout { get }
}
final class HomeViewModel: HomeProtocol {
typealias T = HomeModel
private var items = [[HomeModel]]()
init() {
var items = [HomeModel]()
for (_, item) in HomeItem.allCases.enumerated() {
items.append(item.homeModel)
}
self.items.append(items)
}
var layout: HomeLayout {
return .rightAligned
}
var numberOfSections: Int {
return 1
}
func numberOfItems(in section: Int) -> Int {
guard section >= 0, section < self.items.count else {
return 0
}
return self.items[section].count
}
func itemFor(index: Int,
section: Int) -> HomeModel? {
guard index >= 0, index < numberOfItems(in: section) else {
return nil
}
return items[section][index]
}
func heightFor(index: Int,
section: Int) -> CGFloat {
return 50.0
}
}
//for better understanding
struct HomeModel {
let name: String
let image: String?
}
In this example, you can see that there is a HomeProtocol that conforms the TableListProtocol. And HomeViewmodel conforms the HomeProtocol.
So HomeViewmodel will have to implement the methods and properties that are defined in the TableListProtocol + HomeProtocol.
So in the example, you can see that heightFor, itemFor, numberOfItems, and numberOfSections methods and behaviors implemented which defined the TableListProtocol.
Previous Post — https://medium.com/@abhinay.mca09/associated-types-generic-protocol-in-swift-edc7b27258e8
If you found this post helpful, please consider sharing it and giving it applause to help others discover it too! 👏👏
Happy Coding!🧑🏻💻
🧑🏻💻****************************See you****************************🧑🏻💻