Swift中protocol的三种实现以及mutating关键词

来源:互联网 发布:淘宝的安装服务 编辑:程序博客网 时间:2024/04/29 03:39

Swift中protocol除了可以被class实现外,也可以被structenum实现。而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
原创粉丝点击