1,init():类的初始化方法(构造方法)
class Student: NSObject { //类属性 var name:String = "" var age:Int = 0 //类构造函数 init(newName:String,newAge:Int){ self.name = newName self.age = newAge } //成员函数 func run() -> String { return "\(name) can run" } }
var student = Student(newName:"baibai",newAge:31) student.name = "张三" print(student.name) print(student.age) print(student.run())
2、使用get和set来间接获取/改变其他属性的值
class Calcuator{ var a:Int = 1; var b:Int = 1; var sum:Int{ get{ return a + b } set(val){ b = val - a } } } let cal = Calcuator() print(cal.sum)//2 cal.sum = 5 print(cal.b)//4
3、对于set有简写方法,简写时,新赋的值默认为newValue
class Calcuator{ var a:Int = 1; var b:Int = 1; var sum:Int{ get{ return a + b } set{ b = newValue - a } } } let cal = Calcuator() print(cal.sum)//2 cal.sum = 5 print(cal.b)//4
3、只有get方法
class Calcuator{ var a:Int = 1; var b:Int = 1; var sum:Int{ return a + b } } let cal = Calcuator() print(cal.sum)//2
4、属性观察者,类似于触发器。用来监视属性的除初始化之外的属性值变化,当属性值发生改变时可以对此作出响应。有如下特点:
- 不仅可以在属性值改变后触发didSet,也可以在属性值改变前触发willSet。
- 给属性添加观察者必须要声明清楚属性类型,否则编译器报错。
- willSet可以带一个newName的参数,没有的话,该参数默认命名为newValue。
- didSet可以带一个oldName的参数,表示旧的属性,不带的话默认命名为oldValue。
- 属性初始化时,willSet和didSet不会调用。只有在初始化上下文之外,当设置属性值时才会调用。
- 即使是设置的值和原来值相同,willSet和didSet也会被调用
class People: NSObject { //属性 var firstName:String = "" var lastName:String = "" var nickName:String = "" //计算属性 var fullName: String { get { return nickName + " " + firstName + " " + lastName } } //带属性监视器的普通属性 var age:Int = 0 { //我们需要在age属性变化前做点什么 willSet { print("Will set an new value \(newValue) to age")//newValue = 30 } didSet { print("age filed changed form \(oldValue) to \(age)")//oldValue = 0 ,age = 30 if age<10 { nickName = "Little" }else { nickName = "Big" } } } func toString() -> String { return "Full Name: \(fullName)" + ",Age:\(age)" } } let p = People() p.firstName = "Li" p.lastName = "lei" p.age = 30 print(p.toString())