方法是与某些特定类型相关联的函数
实例方法为给定类型的实例封装了具体的任务与功能
类、结构体、枚举都可以定义实例方法,也都可以定义类型方法
在OC中,类是唯一能定义方法的类型
1 实例方法 (Instance Methods)
- 实例方法只能被它所属的类的某个特定实例调用
1 | class Counter { |
- 方法的局部参数名称和外部参数名称 (Local and External Parameter Names for Methods)
1 | class Counter2 { |
- self 属性(The self Property):
self
完全等同于该实例本身。
消除方法参数 x 和实例属性 x 之间的歧义:
1 | struct Point { |
- 在实例方法中修改值类型(Modifying Value Types from Within Instance Methods)
结构体和枚举的属性不能在它的实例方法中被修改(因为结构体和枚举是值类型),但可通过mutating
(可变方法)修改。
1 | struct Point2 { |
- 在可变方法中给 self 赋值(Assigning to self Within a Mutating Method)
1 | struct Point3 { |
2 类型方法 (Type Methods)
static
class
在类型方法的方法体(body)中,self
指向这个类型本身,而不是类型的某个实例。
1 | struct LevelTracker { |
playground文件在andyRon/LearnSwift