简体   繁体   English

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

[英]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.我想获取 newRecordLat 和 newRecordLong 并将它们保存为函数外部的变量。 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.它们当前以 CLLocationDegrees 输出,而不是字符串、整数、浮点数或双精度数。 I did read somewhere that CLLocationDegrees is a 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
}

You should declare your newRecordLat and newRecordLong variables as properties of your class.您应该将newRecordLatnewRecordLong变量声明为类的属性。 To do this, move both declarations out side of textFieldShouldReturn(_:) .为此,请将两个声明移出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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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