var num1 : Int = 0 var num2 : Int = 5 /// 1.计算属性 var num3 : Int{ return num1 + num2 } /// 2.闭包属性 private lazy var num4 : Int = { return num1 + num2 }() override func viewDidLoad() { super.viewDidLoad() print(num3) print(num4) }
2.类属性
class Student: NSObject { /// 类属性 static var score : Int = 0} override func viewDidLoad() { super.viewDidLoad() Student.score = 1 print(Student.score) }
3. 对象属性赋值
class Student: NSObject { var age:Int = 0 ///可选属性: name1 和name2一个意思 var name1:String? var name2:String? = nil} let stu = Student() stu.age = 10 stu.name1 = "1蛋" stu.name2 = "2蛋" print(stu.age) /// 可选属性 解包写法1 if let name = stu.name1{ print(name) } /// 可选属性 解包写法2 guard let name2 = stu.name2 else { return } print(name2)
/// 可选属性 解包写法3
print(stu.name1 ?? "")
4.构造函数: init(){} 是系统默认的构造函数
自定义构造函数:A> 旧语法 可以在 init的()里面直接写上新参数,B>: 在目前3.0后需要加上convenienceclass
class Student: NSObject { var age:Int = 0 ///可选属性: name1 和name2一个意思 var name1:String? var name2:String? = nil /// 系统默认构造函数: 不需要写 self.init(),但是没啥用 override init() { self.name1 = "0" } /**自定义构造函数 * age 和 age1一样, * 使用conveniences需要写上self.init() */ init(age:Int, name:String) { self.age = age self.name1 = name } convenience init(age1:Int, name1:String) { self.init() self.age = age1 self.name1 = name1 } /**2.传入字典 * dict,dict1,dict2,dict3一样, * dict2,dict3在使用时还是字典使用[String:Any] */ init(dict:[String:Any]) { self.age = dict["age"] as? Int ?? 0 self.name1 = dict["name1"] as? String ?? "" } convenience init(dict1:[String:Any]) { self.init() self.age = dict1["age"] as? Int ?? 0 self.name1 = dict1["name1"] as? String ?? "" } init(dict2:Dictionary) { self.age = dict2["age"] as? Int ?? 0 self.name1 = dict2["name1"] as? String ?? "" } convenience init(dict3:Dictionary ) { self.init() self.age = dict3["age"] as? Int ?? 0 self.name1 = dict3["name1"] as? String ?? "" } } let tempStu = Student(age: 10, name: "tempStu") print("tempStu",tempStu.name1 ?? "", tempStu.age)// tempStu tempStu 10 let tempStu1 = Student(age1: 11, name1: "tempStu1") print("tempStu1",tempStu1.name1 ?? "", tempStu1.age)// tempStu1 tempStu1 11 let stu = Student(dict: ["age":18, "name1":"stu"]) print("dict",stu.name1 ?? "", stu.age)// dict stu 18 let stu1 = Student(dict1: ["age":18, "name1":"stu1"]) print("dict1",stu1.name1 ?? "", stu1.age)//dict1 stu1 18 let stu2 = Student(dict2: ["age":18, "name1":"stu2"]) print("dict2",stu2.name1 ?? "", stu2.age)//dict2 stu2 18 let stu3 = Student(dict3: ["age":18, "name1":"stu3"]) print("dict3",stu3.name1 ?? "", stu3.age)//dict3 stu3 18