Swift 始终设置属性所需的初始化器设置

Swift 始终设置属性所需的初始化器设置,swift,uiview,initialization,swift5,Swift,Uiview,Initialization,Swift5,我有这个自定义视图。此视图始终需要使用注释进行实例化 class MapImageLocationPin: UIView { //MARK: - Properties private var annotation: Annotation! //MARK: - Init override init(frame: CGRect) { super.init(frame: frame) configure() }

我有这个自定义视图。此视图始终需要使用注释进行实例化

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)")
    }
}
由于在设置注释之前在self.init中调用configure(),因此上述设置失败(崩溃,无值)

如何解决这个问题

required convenience init(with annotation: Annotation) {
   self.init(frame: .zero)
   self.annotation = annotation
   self.configure()
}
您可以在self.annotation赋值后移动configure函数


您可以在self.annotation赋值后移动configure函数

如果愿意,您可以用一个初始值设定项替换您的
覆盖初始化(frame:CGRect)
和您的
所需的便利初始化(带annotation:annotation)

init(frame: CGRect = .zero, with annotation: Annotation) {
    super.init(frame: frame)
    self.annotation = annotation
    configure()
}

如果愿意,您可以用一个初始值设定项替换
override init(frame:CGRect)
所需的便利性init(with annotation:annotation)

init(frame: CGRect = .zero, with annotation: Annotation) {
    super.init(frame: frame)
    self.annotation = annotation
    configure()
}

谢谢很简单:)我总是被初始化器弄糊涂!我如何使它在设置后成为非可选的注释?欢迎!如果对您合适,您可以将此答案标记为已解决!我不明白你的意思,汉克斯!很简单:)我总是被初始化器弄糊涂!我如何使它在设置后成为非可选的注释?欢迎!如果对您合适,您可以将此答案标记为已解决!我不明白你的意思