mutating关键字的使用
来源:互联网 发布:linux创建用户脚本 编辑:程序博客网 时间:2024/05/16 17:46
Swift中mutating关键字
Swift中protocol的功能比OC中强大很多,不仅能再class中实现,同时也适用于struct
、enum
。
使用 mutating 关键字修饰方法是为了能在该方法中修改 struct 或是 enum 的变量,在设计接口的时候,也要考虑到使用者程序的扩展性。所以要多考虑使用mutating来修饰方法。
首先,先定义一个protocol
protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust()}
在上面,定义了一个ExampleProtocol
,接下来我们写一个class来遵守这个协议
class SimpleClass: ExampleProtocol { var simpleDescription: String = "A very simple class" var anotherProperty: Int = 110 // 在 class 中实现带有mutating方法的接口时,不用mutating进行修饰。因为对于class来说,类的成员变量和方法都是透明的,所以不必使用 mutating 来进行修饰 func adjust() { simpleDescription += " Now 100% adjusted" }}// 打印结果var a = SimpleClass()a.adjust()let aDescription = a.simpleDescription
在 struct
中实现协议ExampleProtocol
struct SimpleStruct: ExampleProtocol { var simpleDescription: String = "A simple structure" mutating func adjust() { simpleDescription += "(adjusted)" }}
在enum
中实现协议ExampleProtocol
enum SimpleEnum: ExampleProtocol { case First, Second, Third var simpleDescription: String { get { switch self { case .First: return "first" case .Second: return "second" case .Third: return "third" } } set { simpleDescription = newValue } } mutating func adjust() { }}
文/此ID想了很久(简书作者)
原文链接:http://www.jianshu.com/p/14cc9d30770a
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
原文链接:http://www.jianshu.com/p/14cc9d30770a
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
0 0
- mutating关键字的使用
- swift mutating关键字的用法
- mutating的使用(swift2.0)
- swift之mutating关键字
- swift之mutating关键字
- swift之mutating关键字
- swift: mutating关键字
- swift之mutating关键字
- swift之mutating关键字
- swift之mutating关键字
- Swift3.0 mutating关键字
- swift之mutating关键字
- swift之mutating关键字【转】
- Swift之mutating关键字全解
- swift结构体的mutating
- 關於觸發器(Trigger)對於變異表(Mutating table)的操作
- 将 PROTOCOL 的方法声明为 MUTATING
- 修改值类型的实例方法 mutating
- C#上传图片源码
- 『詩解』八方捷报随春至,在前尽忠又立功的动物
- SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax
- ogre 引擎 框架追踪 第五章 资源加载之实加载
- Spring入门学习之Spring MVC(part 2)
- mutating关键字的使用
- NGINX+php+mysql centos6.5配置
- 二、node (Express) Ejs Angular 移动端开发
- H5获取向下一个页面传值并接收参数
- js扩展Date对象 日期格式化
- 每日一题(13): poj1836
- 半年了设计的功力大涨
- linux 查看端口被占用
- ORACLE EBS 标准功能预算功能和实例