Swift Firebase-将数据库快照转换为数组

时间:2019-09-11 18:16:30

标签: swift firebase firebase-realtime-database

我在firebase中有一个组引用,如下所示: database

我无法在应用中将成员列表转换为字符串数组。

我正在这样获取数据:

//Reference to each group
let ref = Database.database().reference().child("groups").child(snapshot.key)

//Get the group data from the reference
ref.observeSingleEvent(of: .value, with: { (groupSnap) in
    //Cast data as dictionary [String:Any]
    if let dictionary = groupSnap.value as? [String: Any] {
        //Parse each group object
        if let group = Group.parse(snapshot.key, dictionary) {
            groups.insert(group, at: 0)
        }

        //Escape with group array
        complete(groups)
    }
})

当前正在分析没有成员的数据:

static func parse(_ key: String, _ data: [String:Any]) -> Group? {
    let name = data["name"] as! String
    let category = data["category"] as! String
    let owner = data["owner"] as! String

    return Group(id: key, name: name, category: Group.Category(rawValue: category)!, ownerId: owner, members: nil)
}

如何将成员列表转换为组对象的字符串数组?

1 个答案:

答案 0 :(得分:2)

// example data
let data = [
    // "name": ...
    // "category": ...
    // "owner": ...
    "members": [
        "member1": true,
        "member2": false,
        "member3": true,
        "member4": true
    ]
]

// grabbing the members element like you do in your parse function
let members = data["members"] as! [String: Bool]

let membersAsListOfStrings = Array(members.keys)
print(membersAsListOfStrings) // -> ["member4", "member1", "member3", "member2"]

let filteredMembersAsListOfStrings = Array(members.filter { $0.value }.keys)
print(filteredMembersAsListOfStrings) // -> ["member4", "member3", "member1"]

您正在寻找.keys属性。我相信Swift的所有字典都有这个功能。这段代码在操场上对我来说很好。