【发布时间】:2017-05-19 11:52:44
【问题描述】:
我正在学习 Swift 3,以及它在 Objective-C 方面的独特范式结构,我偶然发现了一种设计模式,我不知道该怎么做。让我直接提出问题。
以前在 Objective-C 中,我们可以在类本身中实现协议/委托。我看到有一个与此非常相似的 Swift 等价物。
例子:
class myClass : UIViewController , UITextFieldDelegate {
// somewhere inside the class we implement the delegate of
// UITextfieldDelegate, something like this
func doSomething(){
theTextField.delegate = self
}
func textFieldDidEndEditing(_ textField: UITextField) {
// works just fine
}
}
现在这正是我们在 Objective-C 中所做的。但现在我得到了另一种在类中实现协议/委托的方法。
class MyClass : UIViewController , UITextFieldDelegate {
func doSomething(){
theTextField.delegate = self
}
}
extension MyClass : UITextFieldDelegate{
func textFieldDidEndEditing(_ textField: UITextField) {
//Even this works fine
}
}
现在我有点困惑。这也是实现委托模式的另一种方式,还是还有更多?这只是一种设计范式还是还有其他目的?
【问题讨论】:
-
这是一篇不错的相关文章:natashatherobot.com/using-swift-extensions
-
根据 Swift 惯例,以大写字母开头的类命名。顺便说一句,您正在扩展
EQHomeViewController而不是MyClass -
@LeoDabus 我的错,请忽略错别字。我已经编辑了它们
标签: ios swift swift3 delegates protocols