gpt4 book ai didi

swift - 在 Swift 函数之外访问变量

转载 作者:行者123 更新时间:2023-11-28 05:35:40 25 4
gpt4 key购买 nike

如何从内部获取 firstName 的值:

func saveImage(name: String, postURL:URL, completion: @escaping ((_ url: URL?) -> ())){

//Get sspecific document from current user
let docRef = Firestore.firestore().collection("users").whereField("uid", isEqualTo: Auth.auth().currentUser?.uid ?? "")

var firstName = ""

// Get data
docRef.getDocuments { (querySnapshot, err) in

var firstName = ""

if let err = err {
print("ERROR: ")
print(err.localizedDescription)
return
} else if querySnapshot!.documents.count != 1 {
print("More than one documents or none")
} else {
let document = querySnapshot!.documents.first
let dataDescription = document?.data()
firstName = dataDescription?["firstname"] as! String



}

}


// This uploads the data

let dict = ["title": postDescriptionTitle.text!,
"description": postDescription.text!,
"Address": addressField.text!,
"Zipcode": zipcodeField.text!,
"timestamp": [".sv":"timestamp"],
"Author":firstName,
"postUrl": postURL.absoluteString]
as [String: Any]
self.ref.child("post").childByAutoId().setValue(dict)

}

看起来它超出了范围,我如何在不将其存储在另一个变量中的情况下存储或访问它?

如您所见,我正在尝试将变量 firstName 上传到数据库。所以在这部分:“作者”:名字,我应该得到值(value),这样我就可以把它交给作者

最佳答案

只需将“上传数据”部分移动到完成 block 中,如下所示:

  func saveImage(name: String, postURL:URL, completion: @escaping ((_ url: URL?) -> ())) {
//Get sspecific document from current user
let docRef = Firestore.firestore().collection("users").whereField("uid", isEqualTo: Auth.auth().currentUser?.uid ?? "")

// Get data
docRef.getDocuments { (querySnapshot, err) in

if let err = err {
print("ERROR: ")
print(err.localizedDescription)
return
} else if querySnapshot!.documents.count != 1 {
print("More than one documents or none")
} else {
let document = querySnapshot!.documents.first
let dataDescription = document?.data()
let firstName = dataDescription?["firstname"] as! String
// This uploads the data
let dict = ["title": self.postDescriptionTitle.text!,
"description": self.postDescription.text!,
"Address": self.addressField.text!,
"Zipcode": self.zipcodeField.text!,
"timestamp": [".sv":"timestamp"],
"Author": firstName,
"postUrl": postURL.absoluteString] as [String: Any]
self.ref.child("post").childByAutoId().setValue(dict)
}
}
}

此外,您在 saveImage 函数中使用完成参数是为了什么?

关于swift - 在 Swift 函数之外访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58739694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com