Swift 中的方法是與特定類型(類和結構體)相關的函 數。函數
實例方法 隸屬於某個特定類型(類或結構體)實例函數。 class Counter{this
var count = 0spa
funcincrement() {.net
count++orm
}對象
funcincrementBy(amount: Int) {ci
count += amountrem
}it
func reset() {class
count = 0
}
}
let counter = Counter()
// the initial countervalue is 0 counter.increment()
// the counter's valueis now 1 counter.incrementBy(5)
// the counter's valueis now 6 counter.reset()
// the counter's valueis now 0
使用 self
this 表明當前對象。 實例:
struct Point {
var x =0.0, y = 0.0
func isToTheRightOfX(x:Double) -> Bool {
return self.x >
}
}
let somePoint = Point(x: 4.0, y: 5.0)
if somePoint.isToTheRightOfX(1.0) {
println("This point is to the right of theline where x
== 1.0")
}
Swift交流討論論壇論壇:http://www.cocoagame.net
歡迎加入Swift技術交流羣:362298485