I'm trying to make a simple class to be used as the annotations for my MKMapView
. I'm fetching data that i want to parse into these annotation objects, and figure it would be a good idea to initialize an annotation with a dictionary, and do all the parsing in this model class instead of in a UIViewController
. I can't seem to get rid of complier errors though, whenever i try to fix one, a different one shows up.
Currently getting a 'Property self.coordinate
not initialized at implicitly generated super.init
call. Calling super.init()
only produces a different error 'Property self.coordinate
not initialized at super.init
call', no matter where i make the super.init()
call in the method. Any help would be really appreciated! Here's what my code looks like now.
import Foundation
import MapKit
class Student: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String
var subtitle: String
init(dictionary: Dictionary<String, AnyObject>) {
if let first = dictionary["firstName"] as? String {
if let last = dictionary["lastName"] as? String {
self.coordinate = CLLocationCoordinate2DMake(dictionary["latitude"] as! Double, dictionary["longitude"] as! Double)
self.title = first + " " + last
if let mediaURL = dictionary["mediaURL"] as? String {
self.subtitle = mediaURL
}
}
}
}
}
In swift you most have all variables initialize before super.init unless declared optional, in your case you have two variables that need to be initialized, because you are initializing your variables inside an is statement swift is not sure if it will actually be initialize if the if statement fail. Change your code to:
var coordinate: CLLocationCoordinate2D?
var title: String?
var subtitle: String?
In case you really don't care if those variables are initialize, or make sure to initialize them with something in the init method.
In the endo you with all variables initialized and/or optional you will be able to call: super.init()
I hope that helped you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With