0
class User {
    var uid : String
    var profileImageURL : String

    init(uid : String, profileImageURL : String) {
        self.uid = uid 
        self.profileImageURL = profileImageURL
    }
}

如果我的项目从上面的用户模型开始,并且我有一个大规模的应用程序,其中这个用户在超过 20 个文件中被初始化,如果我要进入并添加一个新的必需属性,例如年龄,我将不得不为每个文件修复我的初始化程序。更糟糕的是,我必须在每个初始化程序之后进入并在自己的行上设置新属性。

如果我被要求在生产过程中添加 25 个新属性,这将是一场噩梦。

处理这种未来可能会发生变化的大型模型的最佳方法是什么?

4

2 回答 2

2

I would not initialise an object in 20+ location. That makes the code fragile. Put an extra layer like user management where you can ask the current user / ask for any user. And make the init there, in one single place.

于 2018-11-15T09:03:07.103 回答
1

你做这样的事情

class User {

    var uid : String
    var profileImageURL : String

    init(all : [String:Any]) {
        self.uid = all["uid"] as? String ?? ""
        self.profileImageURL = all["profileImageURL"] as? String ?? ""
    }
}

或者写一个 Codable 类直接解码字典

于 2018-11-15T08:51:04.930 回答