How multiple inheritances work

I'm following a code on a post.

I found assigning line (manager.delegate = self)

class LocationManager: NSObject, CLLocationManagerDelegate, ObservableObject {
@Published var region = MKCoordinateRegion()
private let manager = CLLocationManager()
override init() {
super.init()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    locations.last.map {
        region = MKCoordinateRegion(
            center: CLLocationCoordinate2D(latitude: $0.coordinate.latitude, longitude: $0.coordinate.longitude),
            span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5)
        )
    }
}

}

In documentation, CLLocationManager has delegate property(CLLocationManagerDelegate), so I misunderstood I have to initiate CLLocationManagerDelegate for it. but it is protocol, I can't

What happen when super.init()?
and how manager.delagate = self works?

What you are accomplishing in your code snippet is making your LocationManager a delegate of the CLLocationManager that you instantiated in your initialization method. CLLocationManager has a property delegate that points to the address of a class instance that implements the requirements of the CLLocationManagerDelegate. In your case, it's the instance of LocationManager you are initializing (self). Because your class conforms to the CLLocationManagerDelegate protocol, you have implemented the requirements of the protocol with variables/methods enclosed in your LocationManager class. You start the CLLocationManager instance updating locations (manager.startUpdatingLocation()). When the location manager performs actions, it will call methods in your class as the delegate for the manager, as defined in the protocol. The point in the processing at which your methods are invoked are defined in the CLLocationManager documentation.

Remember, Swift protocols are NOT executable. The protocol provides a set of requirements that must be satisfied by a conforming type (class, struct, enum). Thus, to "initialize" a protocol does not make sense, however, the protocol could specify an init() routine that conforming types must provide in order to satisfy the protocol conformance requirements.

Swift does not support multiple inheritance in the manner of other languages like C++. It's more along the lines of Java interfaces, generalized to all types.

1 Like

super.init invokes the LocationManager super-class (NSObject) initializer to initialize the state of the super class to initial conditions. Note that NSObject is the only class for which LocationManager derives from. All other "inheritance" specifications are protocols that are specifications, not executable code.

Terms of Service

Privacy Policy

Cookie Policy