Swift中protocol的三种实现以及mutating关键词
来源:互联网 发布:淘宝的安装服务 编辑:程序博客网 时间:2024/04/29 03:39
Swift中
protocol
除了可以被class
实现外,也可以被struct
和enum
实现。而mutating
关键词则出现在当你用struct
或者enum
来实现协议并且在协议方法中修改变量的值得时候,用mutating
来修饰协议方法。
首先,定义一个protocol
// 协议protocol VehicleProtocol { // 颜色 var color: UIColor{get set} // 改变颜色(假定changeColor()方法要改变 color 的值,则需要用 mutating 关键词修饰) mutating func changeColor()}
结构体实现协议
// 结构体实现协议struct StructProtocol: VehicleProtocol { var color: UIColor = UIColor.blueColor() // 此处需要 mutating 关键词修饰 mutating func changeColor() { color = UIColor.redColor() }}
类实现协议
// 类实现协议class ClassProtocol: VehicleProtocol { var color: UIColor = UIColor.blueColor() // 此处 不需要使用 mutating 关键词来修饰 func changeColor() { color = UIColor.greenColor() }}
枚举实现协议
// 枚举实现协议enum EnumProtocol: VehicleProtocol { case first(UIColor) var color: UIColor { get { switch self { case .first(UIColor.blueColor()): return UIColor.blueColor() case .first(UIColor.redColor()): return UIColor.purpleColor() default: return UIColor.whiteColor() } } set { switch self { case .first(_): self = .first(newValue) } } } // 此处需要 mutating 关键词修饰 mutating func changeColor() { switch self { case .first(UIColor.blueColor()): self = .first(UIColor.redColor()) default: self = .first(UIColor.whiteColor()) } } }
本文代码链接:https://github.com/zhangzhaopds/Protocol_mutating.git
0 0
- Swift中protocol的三种实现以及mutating关键词
- swift protocol mutating
- swift mutating关键字的用法
- swift结构体的mutating
- 将 PROTOCOL 的方法声明为 MUTATING
- swift 中,protocol的optional方法
- Swift中使用protocol的注意事项
- c++中static关键词的三种作用
- swift之mutating关键字
- swift之mutating关键字
- swift之mutating关键字
- swift之mutating
- swift: mutating关键字
- swift之mutating关键字
- swift之mutating关键字
- swift之mutating关键字
- swift之mutating关键字
- swift的protocol
- 《从零开始学Swift》学习笔记(Day 31)——存储属性
- 《现代操作系统(中文第三版)》课后习题——第二章 进程与线程
- 短信验证码开发教程 - 4.后端篇
- JSP实现图片上传,Eclipse无法保存图片
- OSI七层网络协议与TCP/IP五层网络架构
- Swift中protocol的三种实现以及mutating关键词
- 常见的几道基础java题
- 前进是写在基因里的——底层社会生存指南
- Medium 69题 Sqrt(x)
- TCP与UDP的区别
- Android Fragment讲解
- docker 命令总结 v1.12
- 在Mac上搭建HLS视频直播
- HBase备份之导入导出