Swift中的子类不会继承其超类的初始化程序 [英] Subclass in Swift does not inherit initialiser of its superclass
问题描述
在尝试对NSBezierPath
进行子类化时,我偶然发现了一个非常奇怪的问题.
I have stumbled upon a very strange issue when trying to subclass NSBezierPath
.
下面是我的子类的定义:
Below is the definition of my subclass:
class OSBezierPath: NSBezierPath {
func addLineToPoint(point:CGPoint) {
self.lineToPoint(point)
}
}
除了无法访问NSBezierPath
的某些初始化程序外,该子类的工作原理也不同.例如,下面的行无效:
This subclass works apart from the fact that I cannot access some of the initialisers of the NSBezierPath
. For example, line below is invalid:
let path = OSBezierPath(ovalInRect: rect)
编译器抛出错误
调用中的额外参数'ovalInRect'
Extra argument 'ovalInRect' in call
此错误的原因
另一个问题对此原因进行了很好的解释.但是,建议的答案对我来说效果不佳,因为我要实现的目标是在iOS和Mac OS上都使用OSBezierPath
.
Cause of this bug
Cause of this bug is well-explained in another question. However, the suggested answer doesn't work well for me because what I am trying to achieve is to use OSBezierPath
on both iOS and Mac OS.
我的原始代码是这样的:
My original code read like this:
#if os(iOS)
typealias OSBezierPath = UIBezierPath
#else
class OSBezierPath: NSBezierPath {
func addLineToPoint(point:CGPoint) {
self.lineToPoint(point)
}
}
#endif
此代码不起作用,但是我发现有2个变通方法,比起另一个问题的建议答案,它更适合我的目的.
This code doesn't work, but I have found 2 workarounds which are more elegant for my purpose than the suggested answer in another question.
推荐答案
第一个解决方案
此解决方案使用扩展名将功能添加到NSBezierPath
,这将使其能够以与UIBezierPath
相同的方式绘制线条.
1st solution
This solution uses extension to add a function to NSBezierPath
which will allow it to draw lines in the same way as UIBezierPath
.
#if os(iOS)
typealias OSBezierPath = UIBezierPath
#else
typealias OSBezierPath = NSBezierPath
extension OSBezierPath {
func addLineToPoint(point:CGPoint) {
self.lineToPoint(point)
}
}
#endif
这避免了任何潜在的错误,因为不涉及子类.因此,请在下面一行:
This avoids any potential bug because there is no subclassing involved. Therefore, line below:
let path = OSBezierPath(ovalInRect: rect)
实际上翻译为:
let path = NSBezierPath(ovalInRect: rect)
所以编译器很高兴:)
第二个解决方案使用了UIBezierPath
的类函数已在Xcode 7中转换为适当的初始化程序这一事实,因此,下面的代码将起作用:
Second solution uses the fact that class functions of UIBezierPath
were converted to proper initialisers in Xcode 7. So, code below will work:
#if os(iOS)
class OSBezierPath: UIBezierPath {
func lineToPoint(point:CGPoint) {
self.addLineToPoint(point)
}
}
#else
typealias OSBezierPath = NSBezierPath
#endif
这允许我们通过在iOS和Mac OS上调用lineToPoint
来使用OSBezierPath
.
This allows us to use OSBezierPath
by calling lineToPoint
on both iOS and Mac OS.
这篇关于Swift中的子类不会继承其超类的初始化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!