实例方法 在 Swift 语言中,实例方法是属于某个特定类、结构体或者枚举类型实例的方法。 实例方法提供以下方法:
实例方法要写在它所属的类型的前后大括号({})之间。 实例方法能够隐式访问它所属类型的所有的其他实例方法和属性。 实例方法只能被它所属的类的某个特定实例调用。 实例方法不能脱离于现存的实例而被调用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 import Cocoaclass Counter { var count = 0 func increment () { count += 1 } func incrementBy (amount : Int ) { count += amount } func reset () { count = 0 } } let counter = Counter ()counter.increment() counter.incrementBy(amount: 5 ) print (counter.count)counter.reset() print (counter.count)
方法的局部参数名称和外部参数名称 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import Cocoaclass multiplication { var count: Int = 0 func incrementBy (first no1 : Int , no2 : Int ) { count = no1 * no2 print (count) } } let counter = multiplication()counter.incrementBy(first: 800 , no2: 3 ) counter.incrementBy(first: 100 , no2: 5 ) counter.incrementBy(first: 15000 , no2: 3 )
self 属性 类型的每一个实例都有一个隐含属性叫做self,self 完全等同于该实例本身。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 import Cocoaclass calculations { let a: Int let b: Int let res: Int init (a : Int , b : Int ) { self .a = a self .b = b res = a + b print ("Self 内: \(res) " ) } func tot (c : Int ) -> Int { return res - c } func result () { print ("结果为: \(tot(c: 20 )) " ) print ("结果为: \(tot(c: 50 )) " ) } } let pri = calculations(a: 600 , b: 300 )let sum = calculations(a: 1200 , b: 300 )pri.result() sum.result()
在实例方法中修改值类型 Swift 语言中结构体和枚举是值类型。一般情况下,值类型的属性不能在它的实例方法中被修改。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import Cocoastruct area { var length = 1 var breadth = 1 func area () -> Int { return length * breadth } mutating func scaleBy (res : Int ) { length *= res breadth *= res print (length) print (breadth) } } var val = area(length: 3 , breadth: 5 )val.scaleBy(res: 3 ) val.scaleBy(res: 30 ) val.scaleBy(res: 300 )
类型方法 类型本身调用的方法,这种方法就叫做类型方法。
声明结构体和枚举的类型方法,在方法的func关键字之前加上关键字static。类可能会用关键字class来允许子类重写父类的实现方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 mport Cocoa class Math { class func abs (number : Int ) -> Int { if number < 0 { return (- number) } else { return number } } } struct absno { static func abs (number : Int ) -> Int { if number < 0 { return (- number) } else { return number } } } let no = Math .abs(number: - 35 )let num = absno.abs(number: - 5 )print (no)print (num)