以下のクラスは、そのプロパティを変更するには変異の機能を提供します。突然変異関数を使用してクラスプロパティを設定する方法は?
class Person {
struct Location {
var coordinate: CLLocationCoordinate2D!
var city: String?
mutating func setLocationNameFromCoordinate(completion:(()->())?) {
let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
CLGeocoder().reverseGeocodeLocation(location) { (placemarks: [CLPlacemark]?, error: NSError?) in
guard let city = placemarks?.first?.locality where error == nil else {
return
}
self.city = city //1
completion?()
}
}
}
var location: Location?
}
機能はそれほどのように呼ばれている:
person.location?.setLocationNameFromCoordinate() {
print(person.location?.city) //2
}
しかし、都市名が設定されている1
で、内側からそれを見て位置Structであるが、2
には都市名がオブジェクトに設定されていない。私はここで間違って何をしていますか?
@Hamishはい:
a.location?.city
編集1と同じである
私は閉鎖して、それ自身の位置を通過し、私はそれの価値を確認しました'person.location?.coordinate'には値があります。 – Manuel
'reverseGeocodeLocation'が非同期に動作するため、これは動作しません。都市を設定する補完ハンドラは 'print'行のかなり後に呼び出されます。 – vadian
@vadianの場合、実際には変換関数も補完ハンドラを持っているので、 'reverseGeocodeLocation'が完了したときにのみprintを呼び出しています。コードを更新しました。 – Manuel