Swift 实例方法&类型方法(九)
2016-03-29 00:12
330 查看
iOS交流群: 498143780 一起学习
/// 第一:struct没有继承的功能,而class是可以继承的,这是面向对象语言的核心能力,class当然会有这个能力。
/// 第二: 体现在内存使用上,struct是通过值传递,而class是通过引用传递的,举个简单的例子window对象一定会选择设计成class的实例,而不应该是struct的,通常我们一定不想在设备中拷贝出多个window对象来,对么?
解释来自:
http://blog.objcc.com/swift-struct-class/
override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let counter = Counter() counter.reset() print(counter.count) // 0 counter.incrementBy(5) print(counter.count) // 5 counter.increment() print(counter.count) // let counter1 = Counter1() counter1.incrementBy(5, numberOfTimes: 10) print(counter1.count) // 50 let point = Point() print(point.isToRightOfX(1)) // print(point.x) }
// 'Counter'类定义了三个個实例方法 class Counter { var count = 0 func incrementBy(amount: Int){ count += amount // count + amount } func reset(){ count = 0 // 重置 count = 0 } func increment(){ self.count++ } }
// 稍微复杂一点的 class Counter1 { var count: Int = 0 func incrementBy(amount: Int, numberOfTimes: Int){ count += amount * numberOfTimes } }
// 下面的例子中,`self`消除方法参数`x`和实例属性`x`之间的歧义 struct Point { var x = 0.0, y = 0.0 func isToRightOfX(x: Double) -> Bool{ print(x) // 1.0 return self.x >= x // self.x = 0 x = 上边赋值1 } }
/// 第一:struct没有继承的功能,而class是可以继承的,这是面向对象语言的核心能力,class当然会有这个能力。
/// 第二: 体现在内存使用上,struct是通过值传递,而class是通过引用传递的,举个简单的例子window对象一定会选择设计成class的实例,而不应该是struct的,通常我们一定不想在设备中拷贝出多个window对象来,对么?
解释来自:
http://blog.objcc.com/swift-struct-class/
相关文章推荐
- Swift里通知的使用NSNotificationCenter
- Swift解析Json返回值为null的问题
- 使用Swift打造动态库SDK和DemoAPP时所遇到的(Xcode7.3)
- 仿QQ侧滑边栏
- 关于Swift中出现dyld: Library not loaded: @rpath/libswiftCore.dylib错误的解决方法
- swift:用UIWebView读取本地html文件
- Swift -- !和?的使用
- swift系统学习控件篇:UITableView+UICollectionView
- Swift学习
- 【swift_3】swift之UITableView和UINavigation视图控制器
- swift 之?和!
- 【swift_2】swift之三大控件 UILabel、UITextField、UIButton 的使用
- 【swift_1】swift基本语法及事例Demo
- Swift 2.2 的新特性
- Swift 2.2 的新特性
- Swift2.0下UICollectionViews拖拽效果的实现
- swift user guide.pdf下载
- Swift-属性、方法、下标
- 利用...来字符检測(swift)
- Swift中实现点击、双击、捏、旋转、拖动、划动、长按手势的类和方法介绍