# Swift 5.1 (11) - 方法

### 方法

Swift中结构体和枚举可以定义方法这是与C和Objective-C的主要区别。

#### 实例方法

``````class Counter {
var count = 0
func increment() {
count += 1
}
func increment(by amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
//调用
let counter = Counter() //!< count : 0
counter.increment()//!<count : 1
counter.increment(by: 5)//!< count : 6
counter.reset()//!< count : 0
``````

`self`属性

``````struct Point {
var x = 0.0, y = 0.0 //!< 必须变量，常量不能被修改
mutating func moveBy(x deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
}
}
var somePoint = Point(x: 1.0, y: 1.0)
somePoint.moveBy(x: 2.0, y: 3.0)
print("当前点： (\(somePoint.x), \(somePoint.y))")//!< 当前点： (3.0, 4.0)"
``````

``````struct Point {
var x = 0.0, y = 0.0 //!< 必须变量，常量不能被修改
mutating func moveBy(x deltaX: Double, y deltaY: Double) {
self = Point.init(x: x + deltaX, y: y + deltaY)
}
}
``````

``````enum SizeType:Int,CaseIterable {
case big,middle,small
mutating func nextCase() {
switch self {
case .big:
self = .middle
case .middle:
self = .small
case .small:
self = .big
}
}
}
//使用
let sizeType = SizeType.allCases
for var item in sizeType {
print("当前的item:\(item)")
item.nextCase()
print("调用方法后:\(item)")
}
``````

#### 类型方法

``````class SomeClass {
//定义
class func someTypeMethod() {
//类方法的实现
}
}
//调用
SomeClass.someTypeMethod()
``````

#### 函数or方法的声明属性`@discardableResult`

`@discardableResult`

``````override init() {
super.init()
instanceMethod()
}

func instanceMethod() -> String {
}
``````

swift 5.1官方编程指南

QiShare(简书)
QiShare(掘金)
QiShare(知乎)
QiShare(GitHub)
QiShare(CocoaChina)
QiShare(StackOverflow)
QiShare(微信公众号)