Search code examples
swiftuiviewinitializationswift5

required initialiser setup to set a property always


I have this custom view. This view always needs to be instantiated with an Annotation.

class MapImageLocationPin: UIView {
    //MARK: - Properties
    private var annotation: Annotation!
    
    //MARK: - Init
    override init(frame: CGRect) {
        super.init(frame: frame)
        configure()
    }
    
    required convenience init(with annotation: Annotation) {
        self.init(frame: .zero)
        self.annotation = annotation
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //MARK: - Configure view
    private func configure() {
        print("Pin initialised! \(annotation.title)")
    }
}

The above setup fails (crash, nil value), because configure() is called in self.init, before the annotation is set.

How to solve this ??


Solution

  • required convenience init(with annotation: Annotation) {
       self.init(frame: .zero)
       self.annotation = annotation
       self.configure()
    }
    

    You can move configure function after self.annotation assignment