Swift方法
Swift 中的方法是與特定類型(類和結構體)相關的函 數。
實例方法 隸屬於某個特定類型(類或結構體)實例函數。 class Counter{
var count = 0
funcincrement() {
count++
}
funcincrementBy(amount: Int) {
count += amount
}
func reset() {
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交流討論論壇論壇:https://www.cocoagame.net
歡迎加入Swift技術交流群:362298485
最後更新:2017-04-03 06:03:10