如何在Swift中为类中的字典创建getter setter方法

时间:2017-10-15 02:30:10

标签: swift dictionary

我有一个名为users的字典。我想从Swift程序中的其他类添加和获取此字典中的数据。我该怎么办?

class Database {

    class func addUsers(){
     // i need to know how to create function like such. 
    }

    var userIDName: [String:String] = [
        "A000123" : "AA",
        "A000345" : "BB",
        "A000343" : "CC"
    ]

}

2 个答案:

答案 0 :(得分:1)

class Database {
    var userIDName = [String: String]()
    func addUser(key: String, value: String) {
        userIDName[key] = value
    }

    func getUsers() -> [String: String] {
        return userIDName
    }
}

您可以添加和获取用户数据,如下所示:

var users: [String:String] = [
        "A000123" : "AA",
        "A000345" : "BB",
        "A000343" : "CC"
    ]

let database = Database()

users.forEach({ (key, value) in
    database.addUser(key: key, value: value) // for adding user
})
print(database.getUsers()) // for getting users

答案 1 :(得分:-1)

听起来您希望将其用作单身人士,如下所示:

class Database {
    static let shared = Database()

    func addUsers(id: String, name: String) { 
        userIDName[id] = name
    }

    var userIDName = [String: String]()
}

// Usage
let database = Database.shared

database.addUsers(id: "A123", name: "AA")
print(database.userIDName["A123"])