如何解决此问题“无法分配给属性:'typ'是仅获取的属性”

时间:2020-06-15 23:30:01

标签: ios swift

class NotificationModel {
    var id: String?
    var typ: NotificationType {

        switch self.typ {
        case .order(let id):
            return .order(id)
        case .product(let id):
            return .product(id)
        case .manager:
            return .manager
        }
    }

    init(_ info: [AnyHashable: Any]) {
        self.id = info[AnyHashable("id")] as? String
        typ = (info[AnyHashable("type")] as? NotificationType)!
    }
}
enum NotificationType {
    case manager
    case product(String)
    case order(String)
}

1 个答案:

答案 0 :(得分:1)

也许,请尝试这种方式:

enum NotificationType: String {
    case manager = "master"
    case product = "product"
    case order = "order"
}

class NotificationModel {
    var id: String?
    var type: NotificationType = .master

    init(_ info: [String: Any]) {
        self.id = info["id"] as? String
        if let strType = info["type"] as? String, let temp = NotificationType(rawValue:strType) {
           self.type = temp
        }       
    }
}