将函数中的值设置为函数外的变量(Swift)

时间:2015-06-26 15:57:36

标签: ios iphone swift cllocation

我想获取newRecordLat和newRecordLong并将它们保存为函数外部的变量。目的是因为我想将这些变量存储在数据库中。它们当前正在CLLocationDegrees中输出,而不是字符串,int,float或double。我确实读过某个地方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
        }


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

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

1 个答案:

答案 0 :(得分:1)

您应该将newRecordLatnewRecordLong变量声明为您班级的属性。为此,请将两个声明移到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
}