您的位置:首页 > 移动开发 > Swift

Swift的protocol与协议扩展

2016-05-03 17:28 459 查看
⭐️苹果为什么将Swift 2.0称为面向协议的语言(Protocol-Oriented Programming):

⭐️协议这个概念在Objective-C中就存在了。所谓协议其实就是一系列可以调用方法的结合。在我们调用的时候就可以将注意力集中在方法本身而不是类的实现。苹果在swift 2.0里面给protocol赋予了更加强大的功能。protocol能够被直接扩展。这样prototol的使用更加灵活方便了。

⭐️应用场景:

1、基于protocol可以被直接扩展的特性,我们可以很方便的实现一些经常被复用的代码。比如上传事件到一些数据分析平台上去。我这里用google analytics作为例子。

//定义protocol
protocol MTLog {
func logEvent(category: String, action: String, label: String?, value: NSNumber?)
}


// 扩展protocol
extension MTLog {
func logEvent(category: String, action: String, label: String? = nil, value: NSNumber? = nil ) {

//Google analytics code

let tracker = GAI.sharedInstance().defaultTracker
let builder = GAIDictionaryBuilder.createEventWithCategory(category, action: action, label: Label, value: Value)
tracker.send(builder.build() as [NSObject : AnyObject])
}
}


那么我们就能在遵循了协议的地方直接使用logEvent(“category”, action:”action”)

2、有人会说这样的修改并没有给我们开发带来多大的便利。那么下面这个特性才是protocol的核心了。

我们的程序会有很多popup的信息,错误信息,版本提示信息等等等等。这时候我们不得不在每个需要用到的viewcontroller中都实现一遍。想不重复代码? 可以! 要么我们写一个UIViewController的基类。要么将viewController作为参数传进函数中。

extension MTLog where Self: UIViewController {
func errorHandle(error: String) {

let alertController = UIAlertController(title: nil, message: error, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
alertController.addAction(cancelAction)

self.presentViewController(alertController, animated: true, completion: nil)
}
}


这是在UIViewController中加的协议,表明只要继承自UIViewController的类,都可以使用协议扩展中的方法,所以我们就可以在任何VC中logEvent了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  swift 扩展 protocol iOS