来源

Official documents

 

方法分为两种:

  • 实例方法(Instance Methods)
  • 类型方法(Type Methods)

 

方法基本和函数一样

实例方法(Instance Methods)

 

定义一个实例方法:

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 

 

方法的参数名称

  • Swift 默认方法的第一个参数名称仅当作内部参数名使用。若需要Swift将其扩展为外部参数名,需要在参数名前加“#”来实现
  • 方法的第二个及后续参数的参数名,会被自动扩展为内部和外部参数名。若要屏蔽这种自动扩展,可以在参数名前加 “-”来实现 
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属性(The self Property)

self代表实例本身

上面例子中的increment方法还可以这样写:

func increment() { 
  self.count++ 
} 

 

变化(mutating)方法

一般情况下,值类型的属性不能在它的实例方法中修改,但是使用变化方法可以修改。

定义一个变异方法需要将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)" 

 

在变化方法中给self赋值
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)之前循环切换。

 

类型方法(Type Methods)

 

  • 声明类的类型方法,在方法的func关键字之前加上关键字class
  • 声明结构体和枚举的类型方法,在方法的func关键字之前加上关键字static。

 

声明类的类型方法

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

posted on 2015-03-21 20:27  道无涯  阅读(145)  评论(0编辑  收藏  举报