I remember back in college how it blew my mind when my professor taught us about generics. This powerful pattern completely changed the way I think about reusable code.
Imagine we want to create a helper function that returns the first item of an array. Simple, right? But if we think about this more deeply, we would need to create a separate function for each type, one for strings, one for numbers, and so on. That's not good, because we would be repeating code.
That's where generics come in. Our function could be simply this:
func getFirstItem<T>(_ items: [T]) -> T? {
items.first
}
Where T here stands for a generic type that we don't know.
let firstName = getFirstItem(["Paul", "John", "Ana"])
// "Paul"
let firstPrice = getFirstItem([10, 20, 30])
// 10
Beautiful, right?
What's nice is that this concept can also be applied to SwiftUI, allowing us to create small units of code that can be shared and tested separately.
Here's an example of it:
struct SectionView<T: Hashable, Content: View>: View {
var title: String
var items: [T]
@ViewBuilder var content: (T) -> Content
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text(title)
.font(.headline)
ForEach(items, id: \.self) { item in
content(item)
}
}
}
}
The SectionView is a generic component that takes any Hashable data and a view builder, then renders each item under a shared title. That means the content can be a simple Text or a complex structure:
SectionView(title: "Favorites", items: ["Paul", "John", "Ana"]) { name in
Text(name)
}
SectionView(title: "Prices", items: [10, 20, 30]) { price in
HStack {
Text("Value: ")
Spacer()
Text("$\(price)")
}
}
Pretty cool, right?
I hope you enjoyed this post. Looking forward to your thoughts in the comments!
Top comments (0)