微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Swift中覆盖多个重载的init()方法

我正在尝试使用以下代码Swift(Xcode Beta 5)中创建自定义NSTextFieldCell子类:

class CustomHighlightTextFieldCell : NSTextFieldCell {

    required init(coder aCoder: NSCoder!) {
        super.init(coder: aCoder)
    }

    init(imageCell anImage: NSImage!) {
        super.init(imageCell: anImage)
    }

    init(textCell aString: String!) {
        super.init(textCell: aString)
    }
}

但是,我在第2和第3个init()声明上收到编译错误

/Users/Craig/projects/.../CustomHighlightTextFieldCell:8:40: Invalid redeclaration of 'init(imageCell:)'
/Users/Craig/projects/.../CustomHighlightTextFieldCell.swift:17:5: 'init(imageCell:)' prevIoUsly declared here

/Users/Craig/projects/.../CustomHighlightTextFieldCell:7:39: Invalid redeclaration of 'init(textCell:)'
/Users/Craig/projects/.../CustomHighlightTextFieldCell.swift:21:5: 'init(textCell:)' prevIoUsly declared here

虽然这里有一些奇怪的编译器错误(我得到通常的“SourceKitService终止,编辑器功能暂时限制.”消息),似乎我在我的方法覆盖中遗漏了一些东西 – 但我不知道是什么.

我假设命名参数,或者至少是参数类型,表明这里有三种不同的init()方法,但显然我错过了这个谜题的关键部分.

编辑:如果我将覆盖添加到第二和第三个init()方法,我有一个单独的问题:

required init(coder aCoder: NSCoder!) {
    super.init(coder: aCoder)
}

override init(imageCell anImage: NSImage!) {
    super.init(imageCell: anImage)
}

override init(textCell aString: String!) {
    super.init(textCell: aString)
}

这个新问题(仅通过添加两个覆盖关键字来调用)似乎几乎与原始问题相矛盾.

/Users/Craig/projects/.../CustomHighlightTextFieldCell.swift:17:14: Initializer does not override a designated initializer from its superclass
/Users/Craig/projects/.../CustomHighlightTextFieldCell.swift:21:14: Initializer does not override a designated initializer from its superclass

解决方法

看起来你的声明(使用覆盖)应该足够了,但是,它们似乎也需要@objc声明.这有效:

class CustomHighlightTextFieldCell : NSTextFieldCell {

    required init(coder aCoder: NSCoder!) {
        super.init(coder: aCoder)
    }

    @objc(initimageCell:)
    override init(imageCell anImage: NSImage!) {
        super.init(imageCell: anImage)
    }

    @objc(initTextCell:)
    override init(textCell aString: String!) {
        super.init(textCell: aString)
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐