Boo*_*oon 7 categories swift swift-extensions swift2
在Objective-C类别中,您可以通过在类中包含类别的标题来引入类别方法引入的扩展功能.
似乎所有Swift扩展都是在没有导入的情况下自动引入的.你如何在Swift中实现同样的目标?
例如:
extension UIView {
// only want certain UIView to have this, not all
// similar to Objective-C, where imported category header
// will grant the capability to the class
func extraCapability() {
}
}
Run Code Online (Sandbox Code Playgroud)
定义一个将作为选择的协议,扩展应该是否可用:
protocol UIViewExtensions { }
Run Code Online (Sandbox Code Playgroud)
然后定义协议的扩展,但仅限于子类UIView(相反的方法不起作用):
extension UIViewExtensions where Self: UIView {
func testFunc() -> String { return String(tag) }
}
Run Code Online (Sandbox Code Playgroud)
定义为具有协议的类也将具有扩展名:
class A: UIView, UIViewExtensions { }
A().testFunc() //has the extension
Run Code Online (Sandbox Code Playgroud)
如果没有定义协议,它也没有扩展名:
class B: UIView {}
B().testFunc() //execution failed: MyPlayground.playground:17:1: error: value of type 'B' has no member 'testFunc'
Run Code Online (Sandbox Code Playgroud)
UPDATE
由于协议扩展不执行类多态,如果需要覆盖函数,我唯一能想到的是子类:
class UIViewWithExtensions: UIView {
override func canBecomeFocused() -> Bool { return true }
}
UIViewWithExtensions().canBecomeFocused() // returns true
Run Code Online (Sandbox Code Playgroud)
这也可以与扩展相结合,但我认为它不再有意义了.
| 归档时间: |
|
| 查看次数: |
1733 次 |
| 最近记录: |