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交流讨论论坛论坛:http://www.cocoagame.net

欢迎添�Swift技术交流群:362298485



原文地址:https://www.cnblogs.com/hrhguanli/p/3964479.html