我有一个自定义的UITableViewCel (没什么特别的),它可以在Xcode6.0上完美地工作。当我尝试用Xcode 6.1编译它时,编译器显示以下错误:
A non-failable initializer cannot chain to failable initializer 'init(style:reuseIdentifier:)' written with 'init?'
下面是单元格的代码:
class MainTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
func setup() {<...>}
}
作为解决方案,编译器提出了Propagate the failure with 'init?'
override init?(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setup()
}
我有点困惑。能否详细说明什么是(non)failable initialiser
以及应该如何使用和覆盖它?
发布于 2014-10-17 22:49:30
在SWIFT1.1(在Xcode6.1中)中,苹果引入了可失败的初始化器--即可以返回nil
而不是实例的初始化器。您可以通过在init
后面放置一个?
来定义一个失败的初始化器。您尝试覆盖的初始化器在Xcode 6.0和6.1之间更改了其签名:
// Xcode 6.0
init(style: UITableViewCellStyle, reuseIdentifier: String?)
// Xcode 6.1
init?(style: UITableViewCellStyle, reuseIdentifier: String?)
因此,要重写,您需要对初始化器进行相同的更改,并确保在以这种方式创建单元格时处理nil
的情况(通过分配给可选的)。
你可以阅读更多关于failable initializers in Apple's documentation的内容。
https://stackoverflow.com/questions/26427007
复制相似问题