Looking for assistance since I am missing something! I have defined a new object called "User".
class User: NSObject {
var userID: String!
var fullname: String!
var imagePath: String!
}
Now I want to iterate through each object one at a time checking the values of some of the fields.
func retrieveUsers() {
let ref = Database.database().reference()
ref.child("users").queryOrderedByKey().observeSingleEvent(of: .value, with: { (snapshot: DataSnapshot) in
let users = snapshot.value as! [String: AnyObject]
self.user.removeAll()
for (key,value) in users {
// HOW DO I REFERENCE A FIELD IN THE USER OBJECT
}
}
Keep in mind that in your code, your
usersobject is of type[String:AnyObject]since you're grabbing it from a database (Firebase?).So, you have an untyped Dictionary to deal with.
You can reference fields on the dictionary by doing users[key] where
keyis aString.Judging by your naming of variables, it looks like you're expecting
usersto be an array rather than a dictionary, but then you're casting it as a dictionary. Without knowing your database schema it's hard to say what's actually happening.But, you most likely want to actually turn your [String:AnyObject] into your actual data type. There are a number of approaches to this, but you may have to write your own decoder.
You may want to add more information about what database you're actually using.
Update: Including an example method for turning your dictionary into your object:
Note that I'm not handling failures -- just putting in empty strings.
You can also look into storing making your model
Codablecompliant and try to convert in and out of JSON. See: How can I use Swift’s Codable to encode into a dictionary?