Swift|Swift 方法
实例方法
import UIKit// 实例方法
class Counter {
var count = 0
func increment() {
count += 1
}func increment(amount: Int) {
count += amount
}func reset() {
count = 0
}
}let counter = Counter()
counter.increment()
print(counter.count)
counter.increment(5)
print(counter.count)
counter.reset()
print(counter.count)
console log 如下
文章图片
实例方法.png
mutating 关键字的使用
注意:结构体和枚举都是值拷贝,默认不能修改实例值,如果要修改方法前面需要加上 mutating 关键字
// mutating 关键字的使用
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(deltaX: Double, deltaY: Double) {
x += deltaX
y += deltaY
}mutating func moveTwo(deltaX: Double, deltaY: Double) {
self = Point(x: x + deltaX, y: y + deltaY)
}
}var somePoint = Point(x: 1.0, y: 1.0)
somePoint.moveBy(2.0, deltaY: 3.0)
print("The point is now at (\(somePoint.x), \(somePoint.y))")somePoint.moveTwo(3.0, deltaY: 4.0)
print("The point is now at (\(somePoint.x), \(somePoint.y))")enum TriStateSwitch {
case off, low, high
mutating func next() {
switch self {
case .off:
self = .low
case .low:
self = .high
case .high:
self = .off
}
}
}var ovenLight = TriStateSwitch.off
ovenLight.next()
if ovenLight == TriStateSwitch.low {
print("ovenLight now is low")
}
ovenLight.next()
if ovenLight == TriStateSwitch.high {
print("ovenLight now is high")
}
console log 如下
文章图片
mutating 关键字的使用.png
【Swift|Swift 方法】类方法 --用class 关键字声明
// 类方法
class SomeClass {
class func someTypeMethod(){
print("SomeClass type method.")
}
}SomeClass.someTypeMethod()
console log 如下
文章图片
类方法.png
实战
// 方法实战
struct LevelTracker {
static var highestUnlockedLevel = 1
var currentLevel = 1static func unlock(level: Int) {
if level > highestUnlockedLevel {
highestUnlockedLevel = level
}
}static func isUnlocked(level: Int) -> Bool {
return level < highestUnlockedLevel
}mutating func advance(level: Int) -> Bool {
if LevelTracker.isUnlocked(level) {
currentLevel = level
return true
} else {
return false
}
}
}class Player {
var tracker = LevelTracker()
let playerName: String
func complete(level: Int) {
LevelTracker.unlock(level + 1)
tracker.advance(level + 1)
}init(name: String){
playerName = name
}
}var player = Player(name: "Argyrios")
player.complete(1)print("highest unlocked level is now \(LevelTracker.highestUnlockedLevel)")player = Player(name: "Beto")
if player.tracker.advance(5) {
print("player is now on level 5")
} else {
print("level 5 has not yet been unlocked")
}
console log 如下
文章图片
方法实战.png
推荐阅读
- 对抗抑郁最好的方法
- 怎样用黑谜速冻膜去黑头,|怎样用黑谜速冻膜去黑头, 最有效的去黑头的方法看这!
- 移动端h5调试方法
- 唱歌教学(导致嗓音损坏的几个常见的错误唱歌方法!)
- 拆书方法训练营
- 数组常用方法一
- Swift中willSet和didSet的简述
- 这份史上最经典的3大学习方法,清华北大学霸都在用!
- 迅捷流程图制作软件的使用方法!
- Hacking|Hacking with iOS: SwiftUI Edition - SnowSeeker 项目(一)