Swift调用super.init前未初始化notificationStyle属性报错如何解决
问题根因
Swift遵循两段式初始化规则:子类自定义的存储属性,必须在调用父类构造函数之前完成赋值,你当前的报错来自required init?(coder aDecoder: NSCoder)构造器:该构造器内没有先给notificationStyle赋值就直接调用了super.init(coder: aDecoder),违反了初始化规则。
解决方案
根据你的使用场景选择对应方案即可:
场景1:不需要通过XIB/Storyboard使用Badge(最符合你要求「实例化必须传notificationStyle」的需求)
直接将required构造器标记为不可用,无需实现完整逻辑:
@available(*, unavailable) required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
该方案下,外部只能调用你提供的两个带notificationStyle参数的构造器实例化Badge,完全满足强制传参的要求。
场景2:需要支持XIB/Storyboard初始化
可选两种实现:
- 方案A:给notificationStyle添加默认值
修改属性定义,补上默认值即可兼容原有逻辑:
var notificationStyle: DefaultTableViewCell.NotificationStyle = .numberedSquare
原有coder构造器不需要调整执行顺序,属性有默认值即可通过编译。
- 方案B:从XIB配置中解码样式参数
先给枚举添加RawValue支持:
enum NotificationStyle: String { case numberedSquare, circle }
调整coder构造器逻辑,先解码属性再调用父类构造:
required init?(coder aDecoder: NSCoder) { let styleRaw = aDecoder.decodeObject(forKey: "notificationStyle") as? String ?? DefaultTableViewCell.NotificationStyle.numberedSquare.rawValue self.notificationStyle = DefaultTableViewCell.NotificationStyle(rawValue: styleRaw) ?? .numberedSquare super.init(coder: aDecoder) setup(notificationStyle: notificationStyle) }
内容的提问来源于stack exchange,提问作者Paulo Rodrigues
相关产品推荐
相关产品推荐

