简体   繁体   English

Xcode 6.1中的可用初始化程序

[英]Failable initializer in Xcode 6.1

I have a custom UITableViewCel (nothing fancy) that works perfectly on Xcode 6.0. 我有一个自定义UITableViewCel(没什么花哨的)在Xcode 6.0上完美运行。 When I try to compile it with Xcode 6.1 the compiler shows the following error: 当我尝试使用Xcode 6.1编译它时,编译器显示以下错误:

A non-failable initializer cannot chain to failable initializer 'init(style:reuseIdentifier:)' written with 'init?'

Here is the code of the cell: 这是单元格的代码:

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() {<...>}
}

As a solution the compiler proposes Propagate the failure with 'init?' 作为解决方案,编译器建议Propagate the failure with 'init?' :

override init?(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    self.setup()
}

I'm a bit confused. 我有点困惑。 Is it possible to elaborate what is a (non)failable initialiser and how it should be used and overrided? 有可能详细说明什么是(non)failable initialiser以及它应该如何使用和覆盖?

With Swift 1.1 (in Xcode 6.1) Apple introduced failable initializers -- that is, initializers that can return nil instead of an instance. 使用Swift 1.1(在Xcode 6.1中),Apple引入了可用的初始化程序 - 也就是说,初始化程序可以返回nil而不是实例。 You define a failable initializer by putting a ? 你通过放置一个?定义一个可用的初始化程序? after the init . init The initializer you're trying to override changed its signature between Xcode 6.0 and 6.1: 您尝试覆盖的初始化程序在Xcode 6.0和6.1之间更改了其签名:

// Xcode 6.0
init(style: UITableViewCellStyle, reuseIdentifier: String?)

// Xcode 6.1
init?(style: UITableViewCellStyle, reuseIdentifier: String?)

So to override you'll need to make the same change to your initializer, and make sure to handle the nil case (by assigning to an optional) when creating a cell that way. 因此,要覆盖您需要对初始化程序进行相同的更改,并确保在创建单元格时处理nil大小写(通过分配给可选项)。

You can read more about failable initializers in Apple's documentation . 您可以在Apple的文档中阅读有关可用初始化程序的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM