Methods 程式範例 — Apple’s The Swift Programming Language

Instance Methods

class Counter {   var count = 0   func increment() {      count += 1   }   func increment(by amount: Int) {      count += amount   }   func reset() {      count = 0   }}let counter = Counter()// the initial counter value is 0counter.increment()// the counter's value is now 1counter.increment(by: 5)// the counter's value is now 6counter.reset()// the counter's value is now 0

The self Property

func increment() {   self.count += 1}

一定要使用 self 的例子:

為了區分參數和 property。

struct Point {   var x = 0.0, y = 0.0   func isToTheRightOf(x: Double) -> Bool {      return self.x > x   }}let somePoint = Point(x: 4.0, y: 5.0)if somePoint.isToTheRightOf(x: 1.0) {   print("This point is to the right of the line where x == 1.0")}// Prints "This point is to the right of the line where x == 1.0"

Modifying Value Types from Within Instance Methods

value type 的 instance method 要加上 mutating 才能修改 property。

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("The point is now at (\(somePoint.x), \(somePoint.y))")// Prints "The point is now at (3.0, 4.0)"

當常數是 value type 時不能修改 property。

let fixedPoint = Point(x: 3.0, y: 3.0)
fixedPoint.moveBy(x: 2.0, y: 3.0)
// this will report an error

Assigning to self Within a Mutating Method

在 struct or enum 的 mutating method 裡可以改變 self

struct 的例子

struct Point {   var x = 0.0, y = 0.0   mutating func moveBy(x deltaX: Double, y deltaY: Double) {      self = Point(x: x + deltaX, y: y + deltaY)   }}

enum 的例子

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.lowovenLight.next()// ovenLight is now equal to .highovenLight.next()// ovenLight is now equal to .off

Type Methods

struct LevelTracker {   static var highestUnlockedLevel = 1   var currentLevel = 1   static func unlock(_ level: Int) {      if level > highestUnlockedLevel { 

highestUnlockedLevel = level
}
} static func isUnlocked(_ level: Int) -> Bool { return level <= highestUnlockedLevel } @discardableResult mutating func advance(to 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(to: level + 1) }
init(name: String) {
playerName = name }}var player = Player(name: "Argyrios")player.complete(level: 1)print("highest unlocked level is now \(LevelTracker.highestUnlockedLevel)")// Prints "highest unlocked level is now 2"player = Player(name: "Beto")if player.tracker.advance(to: 6) { print("player is now on level 6")} else { print("level 6 has not yet been unlocked")}// Prints "level 6 has not yet been unlocked"

彼得潘的 Swift iOS App 開發問題解答集

彼得潘和學生們在開發 iOS App 路上曾經解決的問題集

彼得潘的 iOS App Neverland

Written by

彼得潘的 Swift 程式設計入門,App程式設計入門作者,彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,http://apppeterpan.strikingly.com

彼得潘的 Swift iOS App 開發問題解答集

彼得潘和學生們在開發 iOS App 路上曾經解決的問題集

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade