顾名思义,实例方法就是实例可以调用的方法,下面让我们直接上代码吧
class Counter { var count: Int = 0 func incrementBy(amount: Int, numberOfTimes: Int) { count += amount * numberOfTimes } } let a = Counter() a.incrementBy(1,numberOfTimes:1)
class Counter { var count: Int = 0 func incrementBy(amount: Int, _ numberOfTimes: Int) { count += amount * numberOfTimes } } let a = Counter() a.incrementBy(1,1)
struct Student{ var score = 0 mutating func incrementScore(a:Int){ score += a } }
2. 类方法(Type Methods)
类型方法和实例方法一样用点语法调用。但是,你是在类型上调用这个方法,而不是在实例上调用。下面是如何在SomeClass类上调用类型方法的例子:
和定义类属性一样,结构体中用static关键字,类中用class关键字
struct Student{ var score = 0 static func print(){ println("student") } } class School{ var name = "NB小学" class func print(){ println("school") } } Student.print() //输出:student School.print() //输出:school
原文地址:http://blog.csdn.net/xbenlang/article/details/30263061