I'm building a notification system for my app and I figured out a way to pass multiple types to my model.
I need to define a target, a second target and a third target in this model. These targets are different types according to the notification type. It looks like something like this:
class UserNotification<T1, T2, T3>: Codable {
let notifyType: String
let target: T1
let secondTarget: T2
let thirdTarget: T3
enum CodingKeys: String, CodingKey {
case notifyType = "notify_type"
case target
case secondTarget = "second_target"
case thirdTarget = "third_target"
}
It's working well as it is. The thing is I need to define a notification variable in on of my views so I can pass notifications from my backend. This is where I'm stuck. How can I define my variable so I can cast types according to my notifyType value ?
class NotificationBox: UITableViewCell, CellElement {
private var notification: UserNotification<?, ?, ?> // This is where I'm stuck
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
func setResource(resource: Codable) {
var notification = resource as! UserNotification<Any, Any, Any>
switch(notification.notifyType) {
case "get_badge":
self.notification = notification as! UserNotification<Any, Badge, Any>
case "group_reply":
self.notification = notification as! UserNotification<Message, Debate, Message>
case "level_unlock":
self.notification = notification as! UserNotification<User, Any, Any>
case "get_vote":
self.notification = notification as! UserNotification<Any, Debate, Any>
case "group_follow_argument":
self.notification = notification as! UserNotification<Message, Debate, Message>
case "user_follow_level_unlock":
self.notification = notification as! UserNotification<Any, Any, Any>
case "followed":
self.notification = notification as! UserNotification<Any, Any, Any>
case "group_invitation_new":
self.notification = notification as! UserNotification<Any, Any, Any>
default:
self.notification = notification as! UserNotification<Any, Any, Any>
}
configure()
}
Everything is working quite well excepting the variable definition. I don't know how to do it. I tried to define it as:
private var notification: UserNotification<Any, Any, Any>
But it gives me this error:
Cannot assign value of type 'UserNotification<Any, Badge, Any>' to type 'UserNotification<Any, Any, Any>'