1.類的定義:
class 類名 :父類(可以沒(méi)有父類) {?
屬性入热,和方法
}
事例:
class Person : NSObject{
var age:Int = 0
//override 重寫(xiě) 方法 那么字典中沒(méi)有的字典可以在類中沒(méi)有對(duì)應(yīng)的屬性
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
let p = Person()
p.age = 20
//p.setvalusForKeysWithDictionary(["age":18])
// 類的定義屬性
// 1.存儲(chǔ)屬性:存儲(chǔ)實(shí)例的常量和變量
class Student : NSObject {
var age = 0
var name:String?? //可選類型 默認(rèn)為nil
var mathScore : Double = 0.0
var chinaseScore:Double = 0.0
//? ? 定義一個(gè)方法可以返回平均成績(jī)
func getAverageScore() -> Double {
// 在swift開(kāi)發(fā)中导狡,如果使用當(dāng)前對(duì)象的某一個(gè)屬性而叼,或者調(diào)用當(dāng)前對(duì)象的某一個(gè)方法時(shí)戴甩,可以直接使用愚墓,不需要加self
return? (mathScore + chinaseScore)*0.5
}
// 計(jì)算屬性 swift 建議用計(jì)算屬性
var avg:Double {
return (mathScore + chinaseScore)*0.5
}
// 定義類屬性:
static var courseCount:Int = 0
}
// 給類屬性賦值
Student.courseCount = 2
let stu = Student()
stu.age = 10
stu.name = "LM"
stu.mathScore = 78
stu.chinaseScore = 59.9
print(stu.age)
if let name = stu.name {
print(name)
}
let avg = (stu.mathScore + stu.chinaseScore)*0.5
stu.getAverageScore()
print(stu.avg)
2.類的構(gòu)造函數(shù)與屬性監(jiān)聽(tīng)
2.1類的構(gòu)造函數(shù)
class Person: NSObject {
var name:String?
var age = 0
// 父類方法
override init() {
//在構(gòu)造函數(shù)中酪惭,如果沒(méi)有調(diào)用? super.init() 氯哮,那么系統(tǒng)會(huì)幫助調(diào)用
super.init()
print("chongxie")
}
//自定義構(gòu)造函數(shù)
init(name:String,age:Int) {
self.name = name
self.age = age
}
//? ? init(dict:[String : AnyObject]) {
//? ? ? ? let tempName = dict["name"]
//
//? ? ? ? ////as?最終轉(zhuǎn)成的類型時(shí)一個(gè)可選的類型
//? ? ? ? name = tempName as? String
//? ? ? ? //as!最終轉(zhuǎn)成的類型時(shí)一個(gè)確定的類型
////? ? ? ? age = tempage as! Int
//
//? ? ? ? if let tempage = dict["age"] as? Int {
//? ? ? ? ? ? age = tempage
//? ? ? ? }
//
//
//? ? }
init(dict:[String:AnyObject]) {
super.init()
//? ? ? ? self.setValuesForKeysWithDictionary(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
let p = Person()
let p1 = Person(name:"why",age:18)
print(p1.age)
let p2 = Person(dict: ["name":"LM" as AnyObject,"age":18 as AnyObject])
2.2監(jiān)聽(tīng)屬性的變化
class Person : NSObject {
var name : String? {
//屬性將要改變時(shí)進(jìn)行監(jiān)聽(tīng)
willSet{
//? ? ? ? ? print(name)
print(newValue)
}
//屬性已經(jīng)改變時(shí)進(jìn)行監(jiān)聽(tīng)
didSet {
//? ? ? ? ? ? print(name)
print(oldValue)
}
}// 屬性監(jiān)聽(tīng)器
}
let p = Person()
p.name = "LM"