0

だから私はプログラミングに戻ってきて、問題を抱えています。関数に値を格納しているときに関数が値を返しません。見て、なぜそれが起こっているのか教えていただけますか?

func getLocation() -> NSString {
    manager = OneShotLocationManager()
    var tempLocation: NSString = "" // created an empty string for the var

    manager!.fetchWithCompletion {location, error in
        if let locatie = location {
            tempLocation = String(locatie.coordinate.latitude) + "," + String(locatie.coordinate.longitude)
            print(tempLocation) // It stores a value here but will not show it on the return
        } else if let err = error {
            tempLocation = err.localizedDescription
        }
        self.manager = nil
    }
    return tempLocation // It's not returning anything here.. 
}
4

4 に答える 4

2

fetchWithCompletion関数は非同期であるため、 return ステートメントの後に実行されているため、値を返しません。完了ハンドラーを使用して関数を修正し、設定後にアクセスすることができますtempLocation

func getLocation(completion: (location: String) -> ())  {
    manager = OneShotLocationManager()
    var tempLocation: NSString = "" // created an empty string for the var

    manager!.fetchWithCompletion {location, error in
        if let locatie = location {
            tempLocation = String(locatie.coordinate.latitude) + "," + String(locatie.coordinate.longitude)
            print(tempLocation) // It stores a value here but will not show it on the return
        } else if let err = error {
            tempLocation = err.localizedDescription
        }
        self.manager = nil
        completion(location: tempLocation)
    }
}

この関数は、次の方法で実装できます。

getLocation { (location) -> () in
    print(location)
}
于 2015-10-08T07:04:57.890 に答える
2

関数を終了した後に完了が開始されるので、それが問題だと思います。"" を返し、完了コード内で処理を行います

于 2015-10-07T21:03:01.850 に答える
0

getLocation を呼び出して、fetchWithCompletion クロージャー内で処理を行う必要があります。

func getLocation() {
    manager = OneShotLocationManager()

    manager!.fetchWithCompletion {location, error in
        if let locatie = location {
            tempLocation = String(locatie.coordinate.latitude) + "," + String(locatie.coordinate.longitude)

            //DO THE THINGS YOU NEED TO DO WITH THE LOCATION HERE

        } else if let err = error {
            tempLocation = err.localizedDescription
        }
        self.manager = nil
    }
}
于 2015-10-07T21:56:19.730 に答える