Here is how you can use Generics in Swift.
protocol PPP {
var title: String? {get set}
}
class ABC: PPP {
var title: String?
}
class XYZ: PPP {
var title: String?
}
class Option<T> {
var name: String?
var data: T?
init(name: String?, data: T?) {
self.name = name
self.data = data
}
}
let object1 = ABC()
let option1 = Option(name: "Test1", data: object1)
let object2 = XYZ()
let option2 = Option(name: "Test2", data: object2)
Since classes in Swift doesn't have a default initializer, so create one that accepts 2 parameters - String? and T?.
You can use type(of:) method to identify the type of an object.
print(type(of: option1.data)) //ABC
print(type(of: option2.data)) //XYZ
You can use protocol to access title in both ABC and XYZ.
Conform ABC and XYZ to protocol PPP and implement its title property in both ABC and XYZ.
print(option1.data?.title)
print(option2.data?.title)