struct Teacher {
var name = ""
var age = 0
}
let teacher = Teacher()
//因为 teacher 被声明成了常量,即使name是一个变量属性,也无法修改
teacher.name = "good teacher" //报错
class Student: NSObject {
var name = ""
var age = 0
}
let stu = Student()
stu.name = "good student"
懒加载属性:是指当第一次被调用的时候才会计算其初始值的属性。在属性声明前使用 lazy 来表示延迟存储属性
注意:必须将延迟存储属性声明成变量,因为属性的初始值可能在实例构造完成之后才会得到。而常量属性在构造过程完成之前必须要有初始值,因此无法声明成懒加载属性
class Student: NSObject {
lazy var name = ""
var age = 0
}
let student = Student()
print(student.name)
计算型属性:不直接存储值,而是通过get、set方法来取值或赋值
class Student: NSObject {
var firstName = ""
var lastName = ""
//定义计算属性
var fullName:String {
//定义计算属性的getter方法,该方法的返回值由firstName、lastName两个存储属性决定
get{
return firstName + lastName
}
//定义计算属性的setter方法(默认名称 newValue)
set{
self.firstName = newValue.components(separatedBy: " ")[0]
self.lastName = newValue.components(separatedBy: " ")[1]
}
}
}
let student = Student()
student.fullName = "xiao ming"
print(student.firstName) //xiao
print(student.lastName) //ming
只读属性,则无需set部分
class Student: NSObject {
var firstName = ""
var lastName = ""
var fullName:String {
get{
return firstName + lastName
}
}
}
let student = Student()
student.firstName = "xiao"
student.lastName = "ming"
print(student.fullName) //xiaoming
willSet
在新的值被设置之前调用(willSet
会将新属性值作为常量参数传入,默认名称 newValue
表示)didSet
在新的值被设置之后调用(didSet
会将旧属性值作为参数传入,默认参数名 oldValue
表示)class Student: NSObject {
var name:String = "" {
willSet(newName){
print("新值是:\(newName)")
}
didSet{
print("旧值是:\(oldValue)")
}
}
}
let student = Student()
student.name = "小白"
print("---")
student.name = "小黑"
/*
新值是:小白
旧值是:
---
新值是:小黑
旧值是:小白
*/
注意:父类的属性在子类的构造器中被赋值时,它在父类中的 willSet
和 didSet
观察器会被调用,随后才会调用子类的观察器。在父类初始化方法调用之前,子类给属性赋值时,观察器不会被调用
static
来定义类型属性class Student: NSObject {
static var studentNum:Int = 100
}
print(Student.studentNum) //100