Reputation: 237
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 ??
Upvotes: 0
Views: 39
Reputation: 8347
If you prefer, you can replace your override init(frame: CGRect)
and your required convenience init(with annotation: Annotation)
with just one initializer:
init(frame: CGRect = .zero, with annotation: Annotation) {
super.init(frame: frame)
self.annotation = annotation
configure()
}
Upvotes: 1
Reputation: 664
required convenience init(with annotation: Annotation) {
self.init(frame: .zero)
self.annotation = annotation
self.configure()
}
You can move configure function after self.annotation assignment
Upvotes: 1