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

在Swift中覆盖多个重载的init()方法,第1张

概述我正在尝试使用以下代码在 Swift(Xcode Beta 5)中创建自定义NSTextFieldCell子类: class CustomHighlightTextFieldCell : NSTextFieldCell { required init(coder aCoder: NSCoder!) { super.init(coder: aCoder) } 我正在尝试使用以下代码在 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)    }}
总结

以上是内存溢出为你收集整理的在Swift中覆盖多个重载的init()方法全部内容,希望文章能够帮你解决在Swift中覆盖多个重载的init()方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1008455.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存