How to set a class property using a mutating function?

614 views Asked by At

The following class provides a mutating function to change its property:

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?
}

The function is called like so:

person.location?.setLocationNameFromCoordinate() {
    print(person.location?.city) //2
}

However, at 1 the city name is set, looking at it from inside the location Struct, but at 2 the city name is not set for the object. What am I doing wrong here?

2

There are 2 answers

1
Gnanavadivelu On

You can change a var from outside a struct, but you cannot change it from its own methods. You can try like this.

class Person {

    struct Location {
        var coordinate: CLLocationCoordinate2D!
        var city: String?

        mutating func setLocationNameFromCoordinate(completion: (city: String) -> Void) {

            let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
            CLGeocoder().reverseGeocodeLocation(location) { (placemarks: [CLPlacemark]?, error: NSError?) in

                guard let city = placemarks?.first?.subLocality where error == nil else {
                    return
                }

                self.city = city //Breakpoint1
                completion(city: city)

            }
        }
    }

    var location: Location?
}
3
Klein Mioke On

I write some sample codes, I think it's familiar to yours, and it's result just in right way I think.

enter image description here

I pass the location it self out with closure, and I checked the value of it is the same with a.location?.city

Edit 1:

enter image description here