Reputation: 1950
Is it possible to get something like below using generics in swift? Any help would be appreciated more than anything else.
class ABC {
var title: String?
}
class Option: <T> {
var name: String?
var data: T?
}
let object1 = ABC()
let option = Option(name: "Test", data: object1)
// Getting data again
let data = option.data
Upvotes: 0
Views: 51
Reputation: 24341
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)
Upvotes: 1