我可以使用 for-in 循环更新全局数组,并在循环外使用更新后的数组吗? (Swift)

Can I update a global array using a for-in loop, and use the updated array outside of the loop ? (Swift)

我目前正在从 Firestore 获取 ImageUrls,并使用 for-in 循环访问它们。在 for-in 循环中,我使用 .append() 追加到一个全局数组。但是,当我在 for-in 循环之外调用数组时,它是空的。我阅读了对这个 post '' 的回复,这有助于理解我的全局数组是空的,因为在我调用我的数组后正在执行 for-in 循环,以及如何克服这个问题使用闭包时 - 但是使用 for-in 循环时如何获得相同的结果?非常感谢任何直接帮助或指向有用 articles/videos/posts 的链接。

我知道有类似的 posts,但我仔细阅读了它们,只有我上面提到的那个在 swift 中提到了这个问题,所以我读了但仍然挣扎。下面附上代码:

// 我要附加到的全局字符串数组:

var tuwoImageUrls = [String]()

internal var tuwos: [Tuwo]? {
    didSet {
        self.pickerView.pickerView.reloadData()
    }
}

// 从 firestore 中获取文档 ('tuwos') 的函数:

func fetchTuwos(completion handler: @escaping ([Tuwo]?, Error?) -> ()) {
    guard let uid = Auth.auth().currentUser?.uid else {
        return handler(nil, nil)
    }

    Firestore.firestore()
        .collection("tuwos").document(uid).collection("tuwos")
        .getDocuments { (querySnapshot, error) in
            handler(querySnapshot?.documents.compactMap({
                Tuwo(dictionary: [=12=].data())
            }), error)
        }
}

// 调用函数,访问文档以使用 for-in 循环将 ImageUrl 附加到全局数组 ('tuwoImageUrls'):

    fetchTuwos { [weak self] (tuwos, error) in
        self?.tuwos = tuwos

        DispatchQueue.main.async {
            for tuwo in self!.tuwos! {
                let tuwoImageUrl = "\(tuwo.profileImageUrl)"
                self!.tuwoImageUrls.append("\(tuwoImageUrl)")
                self!.pickerView.pickerView.reloadData()
            }
        }

    }

// 在 fetchTuwos 范围之外调用数组的打印语句 returns 空数组

    print("The Urls:" , tuwoImageUrls)

// 我的 'Tuwo' 结构

struct Tuwo {
let name, profileImageUrl, uid: String

init(dictionary: [String: Any]) {
    self.name = dictionary["name"] as? String ?? ""
    self.profileImageUrl = dictionary["profileImageUrl"] as? String ?? ""
    self.uid = dictionary["uid"] as? String ?? ""
}}

希望此解决方案对您有所帮助

fetchTuwos { [weak self] (tuwos, error) in
    self?.tuwos = tuwos
    self?.tuwoImageUrls = tuwos?.map { "\([=10=].profileImageUrl)" } ?? []

    DispatchQueue.main.async { [weak self] in
        self?.pickerView.pickerView.reloadData()
    }
    print("\(tuwoImageUrls)")

}