Swift中的自定义结构初始化

时间:2019-03-02 13:38:44

标签: swift struct properties

struct User {
    var userID: String
    var nameSurname: String
    var email: String
    var password: Int
    var profileImageUrl: String

    var userDictionary: [String: Any] {
        return [
            "userID": userID,
            "nameSurname": nameSurname,
            "email": email,
            "password": password,
            "profileImageUrl": profileImageUrl,

        ]
    }
}

extension User {

    init?(dictionary: [String: Any]) {
        guard let userID = dictionary["userID"] as? String,
            let nameSurname = dictionary["nameSurname"] as? String,
            let email = dictionary["email"] as? String,
            let password = dictionary["password"] as? Int,
            let profileImageUrl = dictionary["profileImageUrl"] as? String else { return nil }

        self.init(userID: userID, nameSurname: nameSurname, email: email, password: password, profileImageUrl: profileImageUrl)
    }



}

let user = User(userID: "burak", nameSurname: "burak", email: "burak", password: 1234, profileImageUrl: "brk")
print(user.userDictionary)

我创建了一个自定义结构来保存我的属性,并编写init方法以字典形式访问,但是我想添加tweets属性(不使用init或绕过init)以访问我的其他结构,但是编译器给我错误。我如何初始化?

var tweets: [Tweet] 

1 个答案:

答案 0 :(得分:0)

只要写

self.init(userID: userID, nameSurname: nameSurname, email: email, password: password, profileImageUrl: profileImageUrl, tweets: [])

否则,声明一个空数组并添加一个显式的init方法,而忽略tweets