PGD*_*Dev 13 extension-methods ios swift swift4
我最近将我的代码迁移到了Swift 4.我面临扩展问题,即
来自扩展的声明无法覆盖
我已经阅读了多个重新发布此问题的帖子.但他们都没有接受下面描述的情景:
class BaseCell: UITableViewCell
{
//Some code here...
}
extension BaseCell
{
func isValid() -> String?
{
//Some code here...
}
}
class SampleCell: BaseCell
{
//Some code here...
override func isValid() -> String? //ERROR..!!!
{
//Some code here...
}
}
Run Code Online (Sandbox Code Playgroud)
根据Apple的说法,
扩展可以为类型添加新功能,但它们不能覆盖现有功能.
但在上面的场景中,我没有覆盖isValid()
扩展中的方法.它在SampleCell
类定义本身中被重写.不过,它正在给出错误.
Tam*_*gel 10
但在上面的场景中,我没有覆盖
isValid()
扩展中的方法.
isValid
在扩展中声明.
错误几乎说如果一个函数以这种方式声明,它就不能被覆盖.
该声明对扩展和扩展都有效.
只要您@objc
使用协议,就可以覆盖扩展名中的声明。在Swift 4.2中:
class BaseClass {}
class SubclassOfBaseClass: BaseClass {}
@objc protocol IsValidable {
func isValid() -> Bool
}
extension BaseClass: IsValidable {
func isValid() -> Bool { return false }
}
extension SubclassOfBaseClass {
override func isValid() -> Bool { return !super.isValid() }
}
BaseClass().isValid() // -> false
SubclassOfBaseClass().isValid() // -> true
Run Code Online (Sandbox Code Playgroud)
在Swift 3中,如果扩展属于从Objective-C派生的类,则您可以覆盖扩展功能(http://blog.flaviocaetano.com/post/this-is-how-to-override- extension-methods /),但是我想它现在在Swift 4中是不可能的。您当然可以做这样的事情:
protocol Validity {
func isValid() -> String?
}
class BaseCell: UITableViewCell, Validity {
}
extension Validity
{
func isValid() -> String? {
return "false"
}
}
class SampleCell: BaseCell {
func isValid() -> String? {
return "true"
}
}
let base = BaseCell()
base.isValid() // prints false
let sample = SampleCell()
sample.isValid() // prints true
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9742 次 |
最近记录: |