In Swift, a protocol can be made generic by using associated types. Associated types give a placeholder name to a type that is used as part of the protocol. The actual type to use for that associated type isn’t specified until the protocol is adopted.
protocol Addition {
associatedtype Item
init(element1: Item, element2: Item)
func add() -> Item
}
struct IntAddition: Addition {
typealias Item = Int
private let element1: Int
private let element2: Int
init(element1: Int, element2: Int) {
self.element1 = element1
self.element2 = element2
}
func add() -> Int {
return element1 + element2
}
}
protocol Numeric {
static func +(lhs: Self, rhs: Self) -> Self
}
extension Int: Numeric {}
extension Double: Numeric {}
struct GenericAddition<T: Numeric>: Addition {
private let element1: T
private let element2: T
init(element1: T, element2: T) {
self.element1 = element1
self.element2 = element2
}
func add() -> T {
return element1 + element2
}
}
let testDouble = GenericAddition(element1: 3.5, element2: 2.9)
testDouble.add() // 6.4
let testInt = GenericAddition(element1: 3, element2: 2)
testInt.add() // 5
Next Post — https://medium.com/@abhinay.mca09/create-a-generic-protocol-for-uitableview-data-source-9c7666565809
If you found this post helpful, please consider sharing it and giving it applause to help others discover it too! 👏👏
Happy Coding!🧑🏻💻
🧑🏻💻****************************See you****************************🧑🏻💻