Search code examples
iosiphoneswiftcllocation

Setting a value in a function as a variable outside the function (Swift)


I want to grab newRecordLat and newRecordLong and save them as a variable outside the function. The purpose is because I want to store these variables in a database. They are currently outputting in CLLocationDegrees, not a string, int, float, or double. I did read somewhere that CLLocationDegrees is a double...

func textFieldShouldReturn(textField: UITextField!) -> Bool {

    localSearchRequest = MKLocalSearchRequest()
    localSearchRequest.naturalLanguageQuery = addressTextField.text
    println(addressTextField.text)
    println("addressTextField.text^^")
    localSearch = MKLocalSearch(request: localSearchRequest)
    localSearch.startWithCompletionHandler { (localSearchResponse, error) -> Void in
        println(localSearchResponse)
        println("localSearchResponse^^")

        if localSearchResponse == nil{
            var alert = UIAlertView(title: nil, message: "Place not found", delegate: self, cancelButtonTitle: "Try again")
            alert.show()
            return
        }


        //GRAB newRecordLat and newRecordLong AND STORE THEM OUTSIDE THE FUNCTION

        var newRecordLat = localSearchResponse.boundingRegion.center.latitude
        var newRecordLong = localSearchResponse.boundingRegion.center.longitude
}

Solution

  • You should declare your newRecordLat and newRecordLong variables as properties of your class. To do this, move both declarations out side of textFieldShouldReturn(_:).

    class MyClass: UITextFieldDelegate {
    
        var newRecordLat: CLLocationDegrees?
        var newRecordLong: CLLocationDegrees?
    
        ...
        ...
    
    
        func textFieldShouldReturn(textField: UITextField!) -> Bool {
            localSearchRequest = MKLocalSearchRequest()
            localSearchRequest.naturalLanguageQuery = addressTextField.text
            println(addressTextField.text)
            println("addressTextField.text^^")
            localSearch = MKLocalSearch(request: localSearchRequest)
            localSearch.startWithCompletionHandler { (localSearchResponse, error) -> Void in
            println(localSearchResponse)
            println("localSearchResponse^^")
                if localSearchResponse == nil {
                var alert = UIAlertView(title: nil, message: "Place not found", delegate: self, cancelButtonTitle: "Try again")
                alert.show()
                return
            }
    
            self.newRecordLat = localSearchResponse.boundingRegion.center.latitude
            self.newRecordLong = localSearchResponse.boundingRegion.center.longitude
    }