011-Swift3.0之方法
一、实例方法
类似于Objective-C中的-方法
1.类的实例方法
class Counter { var count: Int = 0 // 带有一个参数的实例方法 func incrementBy(amount: Int) { count += amount } // 带有两个参数的实例方法 func incrementBy(amount: Int, numberOfTimes: Int) { count += amount * numberOfTimes } // 带有两个参数的实例方法(忽略第一个参数的外部函数名) func incrementBy(_ amount: Int, numberOfTimes: Int) { count += amount * numberOfTimes } // 实例方法中的self // 实例方法中的self指的就是调用该实例方法的实例对象 // 一般的情况下,我们可以省略self,但是当实例方法中的参数和实例中属性重名时,由于参数优先的原则,所以为区分实例属性,必须加上self func add(count: Int) { self.count += count } } // 初始化实例 let counter = Counter() counter.incrementBy(amount: 3) counter.incrementBy(amount: 3, numberOfTimes: 2) counter.incrementBy(3, numberOfTimes: 2) counter.add(count: 2)
2.结构体的实例方法
struct Point { var x = 0.0, y = 0.0 // 结构体是值类型。默认情况下,值类型的属性不能在它的实例方法中被修改 // 如果确实需要在某个特定的方法中修改结构体或者枚举的属性,可以为这个方法选择可变行为(mutating) mutating func moveByX(_ deltaX: Double, y deltaY: Double) { x += deltaX y += deltaY } } // 初始化实例 var somePoint = Point(x: 4.0, y: 5.0) somePoint.moveByX(2.0, y: 3.0)
3.枚举的实例方法
enum TriStateSwitch { case Off, Low, High // 枚举是值类型。默认情况下,值类型的属性不能在它的实例方法中被修改 // 如果确实需要在某个特定的方法中修改结构体或者枚举的属性,可以为这个方法选择可变行为(mutating) mutating func next() { switch self { case .Off: self = .Low case .Low: self = .High case .High: self = .Off } } } // 初始化实例 var ovenLight = TriStateSwitch.Low ovenLight.next()
二、类型方法
类似于Objective-C中的+方法,用关键字static修饰的方法
struct Matrix { var m: [[Int]] var row: Int var col: Int init?(_ arr2d: [[Int]]) { guard arr2d.count > 0 else { return nil } let row = arr2d.count let col = arr2d[0].count for i in 1 ..< row { if arr2d[i].count != row { return nil } } self.m = arr2d self.row = row self.col = col } // 类型方法(关键字static修饰) // 生成单位矩阵 static func identityMatrix(n: Int) -> Matrix? { guard n > 0 else { return nil } var arr2d: [[Int]] = [] for i in 0 ..< n { var row = [Int](repeating: 0, count: n) row[i] = 1 arr2d.append(row) } return Matrix(arr2d) } func printMatrix() { for i in 0 ..< row { for j in 0 ..< col { print(m[i][j], terminator: "\t") } print() } } } // 调用实例的初始化方法创建二维数组 let m = [[1, 2], [3, 4]] if let m = Matrix(m) { m.printMatrix() } // 调用类型方法创建单位矩阵 let mm = Matrix.identityMatrix(n: 5) if let mm = mm { mm.printMatrix() }

浙公网安备 33010602011771号