다음 클래스의 속성을 변경하는 돌연변이 기능을 제공합니다 :돌연변이 함수를 사용하여 클래스 속성을 설정하는 방법은 무엇입니까?
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