本文首發於我的博客html
方法,也就是函數。同其餘語言同樣,在Swift中,也是分爲實例方法和類型方法git
例若有個類Car,有實例方法getnNum
和類型方法getCount
github
class Car {
static var cout = 0
var num = 0
init() {
Car.cout += 1
}
// 類型方法
static func getCount() -> Int { cout }
// 實例方法
func getnNum() -> Int {
num
}
}
let c0 = Car()
let c1 = Car()
let c2 = Car()
print(Car.getCount()) // 3
c0.num = 10
c1.num = 11
print(c1.num) //11
print(c2.num) //0
複製代碼
無論是實例方法,仍是類型方法,裏面均可以調用 self
編程
例如上面的代碼能夠寫成bash
class Car {
static var cout = 0
var num = 0
init() {
Car.cout += 1
}
// 類型方法
static func getCount() -> Int {
self.cout //self表明類型
}
func getnNum() -> Int {
self.num //self表明實例
}
}
複製代碼
mutating
eg:app
struct Point {
var x = 0.0, y = 0.0
func moveBy(deltaX: Double, deltaY: Double) {
x += deltaX //編譯報錯 Left side of mutating operator isn't mutable: 'self' is immutable y += deltaY //編譯報錯 Left side of mutating operator isn't mutable: 'self' is immutable
self = Point(x: x + deltaX, y: y + deltaY) //編譯報錯 Cannot assign to value: 'self' is immutable
}
}
enum StateSwitch {
case low, middle, high
func next() {
switch self {
case .low:
self = .middle//編譯報錯 Cannot assign to value: 'self' is immutable
case .middle:
self = .high//編譯報錯 Cannot assign to value: 'self' is immutable
case .high:
self = .low//編譯報錯 Cannot assign to value: 'self' is immutable
}
}
}
複製代碼
mutating
以後就能夠了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
eg:ide
struct Point {
var x = 0.0, y = 0.0
mutating func moveX(deltaX: Double) -> Double {
x += deltaX
return x
}
}
var p = Point()
p.moveX(deltaX: 10)
複製代碼
由於方法moveX
的返回值沒有使用,編譯器會報警告函數
@discardableResult
就不會警告了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)
複製代碼
參考資料:ui
Swift官方源碼spa