【发布时间】:2016-12-09 06:32:38
【问题描述】:
在 Swift 中,通过使用扩展,您可以在“协议”中提供方法主体。在我的代码中,我可以提供方法主体,请参阅
protocol Test1{
func display()
}
extension Test1{
func display(){
print("display Test1")
}
}
protocol Test2{
func display()
}
extension Test2{
func display(){
print("display Test2")
}
}
class ViewController: UIViewController,Test1,Test2 {
var test1 : Test1?
var test2 : Test2?
func display() {
print("display")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.test1 = self
test1?.display()
self.test2 = self
test2?.display()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我知道我在 ViewController 类中给出了 test1 和 test2 对象的地址。所以“显示”被打印了两次。但是在这两个“协议”中,我都可以使用这些方法。
所以我的问题是为什么苹果给了我在“协议”中编写方法主体的功能?
谁能帮我理解这个功能?
【问题讨论】:
标签: ios swift swift3 protocols