在Swift中结构体和枚举也可以定义方法,而在 Objective-C 中,类是惟一能定义方法的类型。函数
实例方法spa
实例方法是属于某个特定类、结构体或者枚举类型实例的方法,实例方法提供访问和修改实例属性的途径,实例方法的语法与函数彻底一致。实例方法可以隐式访问它所属类型的全部的其余实例方法和属性。实例方法只能被它所属的类的某个特定实例调用。实例方法不能脱离于现存的实例而被调用。code
class Counter { var count = 0 func increment() { count++ } func incrementBy(amount: Int) { count += amount } func reset() { count = 0 } }
和调用属性同样,用点语法(dot syntax)调用实例方法blog
方法的局部参数名称和外部参数名称rem
Swift 默认仅给方法的第一个参数名称一个局部参数名称;默认同时给第二个和后续的参数名称局部参数名称和外部参数名称。这个约定与典型的命名和调用约定相适应,与你在写 Objective-C 的方法时很类似。这个约定还让表达式方法在调用时不须要再限定参数名称。it
下面Counter的另外写法io
class Counter { var count: Int = 0 func incrementBy(amount: Int, numberOfTimes: Int) { count += amount * numberOfTimes } }
incrementBy方法有两个参数: amount和numberOfTimes。默认状况下,Swift 只把amount看成一个局部名称,可是把numberOfTimes即看做局部名称又看做外部名称。下面调用这个方法:class
let counter = Counter() counter.incrementBy(5, numberOfTimes: 3) // counter value is now 15
func incrementBy(amount: Int, #numberOfTimes: Int) { count += amount * numberOfTimes }
这种默认行为使上面代码意味着:在 Swift 中定义方法使用了与 Objective-C 一样的语法风格,而且方法将以天然表达式的方式被调用。变量
修改方法的外部参数名称行为循环
self属性
类型的每个实例都有一个称为“self”的隐式属性,它与实例自己至关。你能够在一个实例的实例方法中使用这个隐含的self属性来引用当前实例。
上面例子中的increment方法还能够这样写
func increment() { self.count++ }
你没必要在你的代码里面常用self。Swift 假定你是指当前实例的属性或者方法。这种假定在上面的Counter中已经示范了:Counter中的三个实例方法中都使用的是count(而不是self.count)
struct Point { var x = 0.0, y = 0.0 func isToTheRightOfX(x: Double) -> Bool { return self.x > x } } let somePoint = Point(x: 4.0, y: 5.0) if somePoint.isToTheRightOfX(1.0) { println("This point is to the right of the line where x == 1.0") } // 输出 "This point is to the right of the line where x == 1.0"(这个点在x等于1.0这条线的右边)
若是不使用self前缀,Swift 就认为两次使用的x都指的是名称为x的函数参数
在实例方法中修改值类型
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) } }
枚举的变异方法能够把self设置为相同的枚举类型中不一样的成员
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()