传递一个struct来构造一个Structs数组

时间:2018-01-26 21:23:46

标签: arrays swift struct google-cloud-firestore

我正在尝试通过创建一个函数来创建一个结构数组,该函数从firestore获取数据,然后将三个结构传递给一个结构数组。这是我的代码:

func fetchUsers() {

    var user1: User
    var user2: User
    var user3: User

    docRef = Firestore.firestore().document("users/user1")
    docRef.getDocument { (docSnapshot, error) in
        guard let docSnapshot = docSnapshot, docSnapshot.exists else { return }
        let myData = docSnapshot.data()
        let fName = myData!["name"] as? String ?? ""
        let fUsername = myData!["username"] as? String ?? ""
        let fBioText = myData!["bioText"] as? String ?? ""

        let user = User(name: fName, username: fUsername, bioText: fBioText, profileImage: #imageLiteral(resourceName: "mauricioprofileimage"))

        user1 = user
    }

    self.docRef = Firestore.firestore().document("users/user2")
        self.docRef.getDocument { (docSnapshot, error) in
        guard let docSnapshot = docSnapshot, docSnapshot.exists else { return }
        let myData = docSnapshot.data()
        let fName = myData!["name"] as? String ?? ""
        let fUsername = myData!["username"] as? String ?? ""
        let fBioText = myData!["bioText"] as? String ?? ""

        let user = User(name: fName, username: fUsername, bioText: fBioText, profileImage: #imageLiteral(resourceName: "trumpprofileimage"))

        user2 = user
    }

    self.docRef = Firestore.firestore().document("users/user1")
        self.docRef.getDocument { (docSnapshot, error) in
        guard let docSnapshot = docSnapshot, docSnapshot.exists else { return }
        let myData = docSnapshot.data()
        let fName = myData!["name"] as? String ?? ""
        let fUsername = myData!["username"] as? String ?? ""
        let fBioText = myData!["bioText"] as? String ?? ""

        let user = User(name: fName, username: fUsername, bioText: fBioText, profileImage: #imageLiteral(resourceName: "amandaprofileimage"))

        user3 = user
    }

    return [user1, user2, user3]
}

let users: [User] = fetchUsers()

我遇到的问题是,当我尝试填充我的用户数组时,它表示它无法识别我在Fetchfuncion中创建的user1,user2和user3。

Ps:我正在使用firestore。谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

将每个请求放入一个组中,并且只有在检索到所有三个用户后,才返回用户数组。你的代码发生了什么,它返回一个空用户数组(或者1-3个不一致),因为这些调用是异步的,所以当数组是时,不保证从firebase请求返回的数据存在返回。

let group = DispatchGroup()

group.enter()
make_async_request_1 {
    // Process response
    group.leave()
}

group.enter()
make_async_request_2 {
    // Process response
    group.leave()
}

group.enter()
make_async_request_3 {
    // Process response
    group.leave()
}
group.notify(queue: .main) {
    // This will run after all 3 group.leave() calls are made
}