Using Generics to reuse collection view cells

Swift Diaries
2 min readMar 13, 2020

Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner.

swift-generics-how-to-770x400.jpg

This is what the Official Swift Documentation says about Generics. We can use Generics to make reusable codes. This is the main advantage of Generics. We will discuss a use case of Generics where we can reuse one UICollectionViewCell in different places in a project.

This will be my UICollectionViewCell consists with a title label and a text field for another text. Assume that a cell UI with this is being used all over the project, but data of different Object models are presented.

struct Subject {
let title: String
let description: String
}
struct Teacher {
let name: String
let address: String
let imageUrl: String
}

Think you need to populate data on same collection view cell using those two different Models or Structs. How would you pass two different types of data? Or in the latter part of the project you may be asked reuse this cell with another kind of data type also. So there should be a sustainable way of implementing the cell.

This will be an ordinary way to setup a cell with different types of data.

@IBOutlet weak var titleLabel: UILabel!func setupCell(with teacher: Teacher? = nil, with subject: Subject? = nil) {
if let teacher = teacher {
titleLabel.text = teacher.name
} else if let subject = subject {
titleLabel.text = subject.title
}
}

As I mentioned above, what if we need to populate another type of model in future?

According to SOLID principles, we should write code that are open for extension, but closed for modification.

So changing the setupCell method signature violates our SOLID principles. Here comes the use of Generics.

For this implementation we will need enum concept and generics concept together.

At the cell return, we can return the cell as below.

let subject = Subject(title: "Generics", description: "Generics are awesome 😎")
cell.setupCell(item: subject, cellType: .subject)
return cell

Likewise you can pass a Teacher object too. See how much easy it is to maintain this code in future. This can improve reusability and maintainability of your code base.

--

--

Swift Diaries

I am an iOS developer and thought of writing day today Swift things for the community :)