Swift的protocol与协议扩展

⭐️苹果为什么将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了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值