标签:
方法分为两种:
方法基本和函数一样
class Counter { var count = 0 func increment() { count++ } func incrementBy(amount: Int) { count += amount } func reset() { count = 0 } }
let counter = Counter() // 初始计数值是0 counter.increment() // 计数值现在是1 counter.incrementBy(5) // 计数值现在是6 counter.reset() // 计数值现在是0
class Counter { var count: Int = 0 func incre(amount: Int, number: Int) { count += amount * number } }
incre方法有两个参数: amount和number。默认情况下,Swift 只把amount当作一个局部名称,但是把number即看作局部名称又看作外部名称。下面调用这个方法:
let counter = Counter() counter.incrementBy(5, numberOfTimes: 3) // counter value is now 15
self代表实例本身
上面例子中的increment方法还可以这样写:
func increment() { self.count++ }
一般情况下,值类型的属性不能在它的实例方法中修改,但是使用变化方法可以修改。
定义一个变异方法需要将mutating关键字放到func之前
struct Point { var x = 0.0, y = 0.0 mutating func moveByX(deltaX: Double, y deltaY: Double) { x += deltaX y += deltaY } }
var somePoint = Point(x: 1.0, y: 1.0) somePoint.moveByX(2.0, y: 3.0) println("The point is now at (\(somePoint.x), \(somePoint.y))") // 输出 "The point is now at (3.0, 4.0)"
struct Point { var x = 0.0, y = 0.0 mutating func moveByX(deltaX: Double, y deltaY: Double) { self = Point(x: x + deltaX, y: y + deltaY) } }
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.Low ovenLight.next() // ovenLight 现在等于 .High ovenLight.next() // ovenLight 现在等于 .Off
上面的例子中定义了一个三态开关的枚举。每次调用next方法时,开关在不同的电源状态(Off,Low,High)之前循环切换。
class SomeClass { class func someTypeMethod() { // type method implementation goes here } } SomeClass.someTypeMethod()
struct LevelTracker { static var highestUnlockedLevel = 1
static func unlockLevel(level: Int) { if level > highestUnlockedLevel {
highestUnlockedLevel = level
} } static func levelIsUnlocked(level: Int) -> Bool { return level <= highestUnlockedLevel } }
2015-03-21
20:27:29
标签:
原文地址:http://www.cnblogs.com/huangzx/p/4356128.html