i'm new to coding in Swift, I have been looking around for some time for a solution to this issue and as of yet unable to find anything that solves my problem.
I am using a function to return some data from Firebase. After many errors and much research, I have managed to get the function 'working' without throwing errors, but the data that is returned is blank. Essentially I am trying to return multiple values and hold them in an array when I call the function.
The data is returning fine from Firebase, when I print out the variable just after setting it, it will print out correctly but when I do the same just before returning the function, it returns blank. If I try to return the function just after setting the data, I get the error "Unexpected non-void return value in void function".
Here is the full code:
func loadClientData(client_id: String) -> (address_1: String, address_2: String, city: String, company_name: String, contact_name: String, county: String, email: String, phone: String, postcode: String, country: String) {
let db = Firestore.firestore()
let userID : String = (Auth.auth().currentUser!.uid)
print("\(userID)/clients/existing/\(client_id)")
let docRef = db.collection("\(userID)/clients/existing/").document(client_id)
var address_1 = ""
var address_2 = ""
var city = ""
var company_name = ""
var contact_name = ""
var county = ""
var email = ""
var phone = ""
var postcode = ""
var country = ""
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let data = document.data()
address_1 = data?["address_1"] as? String ?? ""
address_2 = data?["address_2"] as? String ?? ""
city = data?["city"] as? String ?? ""
company_name = data?["company_name"] as? String ?? ""
contact_name = data?["contact_name"] as? String ?? ""
county = data?["county"] as? String ?? ""
email = data?["email"] as? String ?? ""
phone = data?["phone"] as? String ?? ""
postcode = data?["postcode"] as? String ?? ""
country = data?["country"] as? String ?? ""
print("Company name is \(company_name)") // <---- THIS prints out the company name
} else {
print("client does not exist")
return
}
}
print("Company name is \(company_name)") // <---- THIS prints the company name as blank
return (address_1: address_1, address_2: address_2, city: city, company_name: company_name, contact_name: contact_name, county: county, email: email, phone: phone, postcode: postcode, country: country)
}
This is being called like so:
let companyInfo = loadClientData(client_id: self.items[indexPath.item].company)
print(companyInfo)
And prints out the following:
(address_1: "", address_2: "", city: "", company_name: "", contact_name: "", county: "", email: "", phone: "", postcode: "", country: "")
Thanks in advance for your input.