VeganKid VeganKid - 1 year ago 35
iOS Question

Custom init in Swift Class giving 'property not initialized at implicitly generated super.init call' error?

I'm trying to make a simple class to be used as the annotations for my

. 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
. 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
not initialized at implicitly generated
call. Calling
only produces a different error 'Property
not initialized at
call', no matter where i make the
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

Answer Source

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