Files
SwiftStudy/11 方法.playground/Resources/README.md

79 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

### 方法
枚举、结构体、类都可以定义实例方法、类方法
* 实例方法Instance Method
* 通过实例调用
* 类方法Type Method
* 通过类型调用,用 `static` 或者 `class` 关键字定义
```swift
class Car {
static var cout = 0
init() {
Car.cout += 1
}
static func getCount() -> Int {
// 等价于 self.cout、Car.cout
cout
}
}
let c0 = Car()
let c1 = Car()
let c2 = Car()
// 3
print(Car.getCount())
```
#### self
* 在实例方法中代表实例
* 在类型方法中代表类型
#### mutating
结构体和枚举是**值类型**,默认情况下,值类型的属性不能被自身的实例方法修改。在 `func` 关键字前加 `mutating` 可以允许这种修改行为。
```swift
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(deltaX: Double, deltaY: Double) {
x += deltaX
y += deltaY
// self = Point(x: x + deltaX, y: y + deltaY)
}
}
enum StateSwitch {
case low, middle, high
mutating func next() {
switch self {
case .low:
self = .middle
case .middle:
self = .high
case .high:
self = .low
}
}
}
```
#### @discardableResult
`func` 前面加个 `@discardableResult` ,可以消除:函数调用后返回值未被使用的警告⚠
```swift
struct Point {
var x = 0.0, y = 0.0
@discardableResult mutating
func moveX(deltaX: Double) -> Double {
x += deltaX
return x
}
}
var p = Point()
p.moveX(deltaX: 10)
```