简体   繁体   中英

Access variable outside of function Swift

How can I get the value from firstName from the inside:

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)

}

It looks like it's out of scope, how can I store it or access it without storing it in another variable?

As you can see, I'm trying to upload the variable firstName to the database. So in this part: "Author": firstName , I should be getting the value so I can give it to Author

Just move the "upload data" part inside the completion block like this:

  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)
            }
        }
    }

Also for what are you using the completion argument in your saveImage function?

You can just declare your variable outside of the function, like this:


var firstName: String! // variable declaration

func saveImage(name: String, postURL:URL, completion: @escaping ((_ url: URL?) -> ())){
    //code
    firstName = ""
    //code
}

Now you can use it on the outside of the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM