方法概念:
函数在类,结构体,枚举中就叫方法。
实例方法举例:
class Counter {
var count = 0
func increment() {
count += 1
}
func incrementBy(amount: Int) {
count += amount
}
func reset() {
count = 0
}
}```
#####实例方法需要实例来调用如通过counter 实例调用Counter类中的increment,incrementBy,reset三个方法
let counter = Counter()
// the initial counter value is 0
counter.increment()
// the counter's value is now 1
counter.incrementBy(5)
// the counter's value is now 6
counter.reset()
// the counter's value is now 0```
Mutating关键字
Swift通过Mutating关键字修改实例方法中的值类型数据,例如在moveByX方法前面加上mutating 修改Point中的x和y的值
struct Point {
var x = 0.0, y = 0.0
mutating func moveByX(deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
}
}
var somePoint = Point(x: 1.0, y: 1.0)
somePoint.moveByX(2.0, y: 3.0)
print("The point is now at (\(somePoint.x), \(somePoint.y))")
// Prints "The point is now at (3.0, 4.0)"```
####类型方法
#####类型方法有两种关键字:static和class,class关键字表示该方法在子类中可以重写覆盖。在swift中类、结构体、枚举都有类型方法。
class SomeClass {
class func someTypeMethod() {
// type method implementation goes here
}
}
SomeClass.someTypeMethod()```
类型方法只能访问静态变量(在该变量前也有static关键字修饰的变量)实例方法前面加上mutating 关键字以后可以访问静态变量和实例变量
struct LevelTracker {
static var highestUnlockedLevel = 1
static func unlockLevel(level: Int) {
if level > highestUnlockedLevel { highestUnlockedLevel = level }
}
static func levelIsUnlocked(level: Int) -> Bool {
return level <= highestUnlockedLevel
}
var currentLevel = 1
//mutating 关键字访问实例变量
mutating func advanceToLevel(level: Int) -> Bool {
if LevelTracker.levelIsUnlocked(level) {
currentLevel = level
return true
} else {
return false
}
}
}```
####init方法
#####通过init初始化类中的变量
class Player {
let playerName: String
init(name: String) {
playerName = name
}
}
var player = Player(name: "Argyrios")
Print(player.playerName)```