protocol ItemStoring {
associatedtype DataType
var items: [DataType] { get set}
mutating func add(item: DataType)
}
extension ItemStoring {
mutating func add(item: DataType) {
items.append(item)
}
}
We can create a NameDatabase struct that conforms to the ItemStoring protocol like this
struct NameDatabase: ItemStoring {
var items = [String]()
}
Swift is smart enough to realize that String is being used to fill the hole in the associated type, because the items array must be whatever DataType is.
var names = NameDatabase()
names.add(item: "Siva Mani")
names.add(item: "Mani Siva")
print("Names: \(names.items)")
var mobileNumbers = MobileNumbersDatabase()
mobileNumbers.add(item: 9848022338)
mobileNumbers.add(item: 2233898480)
print("Mobile Numbers: \(mobileNumbers.items)")
Names: ["Siva Mani", "Mani Siva"]
Mobile Numbers: [9848022338, 2233898480]