mutating的使用(swift2.0)
2015-12-09 00:02
435 查看
mutating 可变化,可改变
mutating可使用到的地方:1.结构体,枚举类型中的方法声明为mutating
2.extension中的方法声明为mutating
3.protocol方法声明为mutating
1.修改struct,enum的属性变量:周知swift中结构体(structure)和枚举(enumeration)中是可以包含类方法和实例方法,可是官方不建议在实例方法中修改其属性变量(immutable),在func前加入mutating关键字后,使其属性变量可修改(mutable)
2.在extension中同理
3.可能会被struct或enum实现的protocol方法,需要声明为mutating使实现时可修改其自己的属性变量,同时因为mutating对于class来说是完全透明的,不必担心使用class实现该protocol方法会带来影响
例子:为String添加一个extention 实现appendString(string: String)
import UIKit extension String { mutating func appendString(string: String) { self = self.stringByAppendingString(string) } }
例子:为Array添加一个extention 实现removeObject(object :Generator.Element)
import Foundation extension Array where Element : Equatable { // Remove first collection element that is equal to the given `object`: mutating func removeObject(object : Generator.Element) { if let index = self.indexOf(object) { self.removeAtIndex(index) } } }
例子:struct实现protocol方法
protocol MyProtocol { mutating func MyProtocolDidChange(index: Int) } struct MyStruct: MyProtocol { let index = 4 mutating func MyProtocolDidChange(index: Int) { index = index } }
相关文章推荐
- as在swift中的应用
- swift 学习之UISegmentedControl
- 一步一步学swift之:自己写Api接口-PHP
- 如何创建swift工程
- swift 创建UICollectionView
- swift -懒加载创建view
- swift实际使用中遇到的问题及解决(2)
- Swift学习笔记 -- 流程控制
- swift UITabelVIew - 纯代码自定义tabelViewCell
- swift编码出现Call can throw, but it is not marked with 'try' and the error is not handled错误的解决
- Swift学习之路 -- 枚举和结构体
- 【菜鸟初学Swift】IOS平台常用传感器的使用方式
- Swift!代码实现UI基础控件
- Swift----单列的正确编写方式
- swift 学习之 UIAlertViewController
- 如何使用Instruments诊断App(Swift版):起步
- swift - 动态计算文本高度
- swift学习之UITabelView ----使用xib定义cell
- swift学习之UITabelView ----UITableViewCell
- swift学习之-- UIAlertVIewController - uiactionsheet