Search code examples
iosswiftswift4key-value-codingkeypaths

setValuesForKeysWithDictionary in Swift 4?


It seems like Swift 4 is implementing different method to (void)setValuesForKeysWithDictionary(), what is appropriate replacement to this function in Swift 4?

I have struct of

struct User {
    let name: String?
    let email: String?
}

The dictionaryOfUsers is coming from data structure which value are presented dynamically based on the number of users in the database:

let dictionaryOfUsers = [{key1: "name1", key2 : "name1@xyz.com"}, {key1 : "name2", key2 : "name2@gmail.com"} ]   
let users = [User]

Now I want to use this function to create my user array to create dictionary in Swift 4:

for dictionary in dictionaryOfUsers {
    let user = User()
    user.setValuesForKeysWithDictionary(dictionary) 

and append to users

    users.append(user)
}     

Solution

  • Try this method instead:

    func setValuesForKeys(_ keyedValues: [String : Any])
    

    Sets properties of the receiver with values from a given dictionary, using its keys to identify the properties. The default implementation invokes setValue(_:forKey:) for each key-value pair...

    Your code has many minor issues — and some major issues as well (see matt answer for more info). Anyway, I think this should accomplish what you are after:

    import Foundation
    
    class User: NSObject {
        @objc var name: String!
        @objc var email: String!
    }
    
    let dictionaryOfUsers = [
        ["name": "name1", "email": "name1@xyz.com"],
        ["name": "name2", "email": "name2@gmail.com"]
    ]
    
    var users = [User]()
    for dictionary in dictionaryOfUsers {
        let user = User()
        user.setValuesForKeys(dictionary) 
        users.append(user)
    }