2016-08-25 1 views
1

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

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에는 도시 이름이 오브젝트에 설정되어 있지 않습니다. 여기서 내가 뭘 잘못하고 있니?

+0

@Hamish 예 : a.location?.city

편집 1과 동일

enter image description here

나는 폐쇄와 자기 위치를 통과, 나는 그것의 가치를 확인 'person.location? .coordinate'에는 값이 있습니다. – Manuel

+1

'reverseGeocodeLocation'이 비동기 적으로 작동하기 때문에 이것은 작동하지 않습니다. 도시를 설정하는 완료 핸들러는'print' 라인 이후 훨씬 나중에 호출됩니다. – vadian

+0

@vadian, 돌연변이 함수는 실제로 완료 핸들러도 가지고 있으므로'reverseGeocodeLocation'이 완료되었을 때만 print를 호출합니다. 코드를 업데이트했습니다. – Manuel

답변

1

구조체 외부에서 var를 변경할 수는 있지만 자체 메서드에서 변경할 수는 없습니다. 이런 식으로해볼 수 있습니다.

+0

하지만 mutable struct ('var')가'mutating' 함수로 속성을 수정하는 많은 다른 예제를 봅니다. 그렇다면 왜 내 경우에는 효과가 없습니까? 또한, mutating 속성이 아니라면'mutating' 키워드는 무엇입니까? http://stackoverflow.com/a/26447291/1870795 – Manuel

0

몇 가지 샘플 코드를 작성 했으므로 친숙하다고 생각하며 올바른 결과를 얻었습니다. ,

enter image description here

+0

이것은 Gnanavadivelu의 대답과 같습니다. 나는 Gnanavadivelu의 대답에서 내 의견을 참조하십시오 코드 예제가있는 것만 큼이 구조체가 어떻게 변이 될 수 있는지 알고 싶습니다. – Manuel

+1

@Manuel Gnanavadivelu가 잘못 생각한 것 같습니다. 'mutating'키워드는 함수가 struct의 속성을 변경한다는 것을 의미합니다. 내 편집을보고, 당신과 같은 방식으로 진행됩니다. 그래서 당신의 문제가'돌연변이'와 관련이 없을 수도 있다고 생각합니다.'참조 형 '과 같은 다른 것을 찾아보십시오. –

+0

reverseGeocodeLocation 클로저 외부의 변수를 변경하면 도시 이름이 수정됩니다. http://stackoverflow.com/questions/37851249/swift-mutable-structs-in-closure-of-class-and-struct-behave-differently – Gnanavadivelu

관련 문제