class Person {
    var firstName: String
    var lastName: String
    init(firstName:String, lastName:String){
        self.firstName = firstName
        self.lastName = lastName
    }
    init?(fullName:String) {
        guard let spaceIndex = fullName.rangeOfString(" ")?.startIndex
        else{
            return nil
        }
        self.firstName = fullName.substringToIndex(spaceIndex)
        self.lastName = fullName.substringFromIndex(spaceIndex.successor())
    }
    func fullName() ->String{
        return firstName + " " + lastName
    }
}
let person1 = Person(firstName: "aaaa", lastName: "bbbb")
let person2 = Person(fullName: "full name")
person1.fullName()

類是引用類型

class Person {
    var firstName: String
    var lastName: String
    var career: String?
    
    init(firstName:String, lastName:String, career:String){
        self.firstName = firstName
        self.lastName = lastName
        self.career = career
    }
    init(firstName:String, lastName:String){
        self.firstName = firstName
        self.lastName = lastName
    }
    func fullName() ->String{
        return firstName + " " + lastName
    }
}
let person1 = Person(firstName: "aaa", lastName: "sss", career: "doctor")
let person2 = person1
person2.firstName = "www"
person2.lastName = "rrr"
person2.career = "ceo"
//person2改變之后墨叛,person1也改變了---他們指向的是同一塊內(nèi)存空間(結(jié)構(gòu)體是值類型,指向不同的內(nèi)存空間滓技,改變一個不會影響另一個)
person2
person1
class Person {
    let firstName: String
    let lastName: String
    var career: String?
    
    init(firstName:String, lastName:String, career:String){
        self.firstName = firstName
        self.lastName = lastName
        self.career = career
    }
    init(firstName:String, lastName:String){
        self.firstName = firstName
        self.lastName = lastName
    }
    func fullName() ->String{
        return firstName + " " + lastName
    }
}
let person1 = Person(firstName: "aaa", lastName: "sss", career: "doctor")
//person1.firstName = "sss"不可修改
person1.career = "ceo"http://person1的let類型不會限制內(nèi)存空間中career的類型令漂,但是person1已經(jīng)指向了一塊內(nèi)存空間叠必,而且是let類型纬朝,不可以再指向另一塊
class Person {
    let firstName: String
    let lastName: String
    var career: String?
    
    init(firstName:String, lastName:String, career:String){
        self.firstName = firstName
        self.lastName = lastName
        self.career = career
    }
    init(firstName:String, lastName:String){
        self.firstName = firstName
        self.lastName = lastName
    }
    func fullName() ->String{
        return firstName + " " + lastName
    }
    func changeCareer(newCareer: String) {
        self.career = newCareer
    }
}
let person1 = Person(firstName: "aaa", lastName: "sss", career: "doctor")
person1.changeCareer("CEO")

結(jié)構(gòu)體和枚舉是值類型共苛,改變自身要加mutating

struct Location {
    var x = 0
    var y = 0
    mutating func goEast() {
        self.x += 1//本來不可改變隅茎,加上mutating
    }
}
var location = Location()
location.goEast()

enum Switch {
    case On
    case Off
    mutating func click(){
        switch self {
        case On:
            self = .Off
        case Off:
            self = .On
        }
    }
}
var button = Switch.Off
button.click()

類的等價

class Person {
    var firstName: String
    var lastName: String
    var career: String?
    
    init(firstName:String, lastName:String, career:String){
        self.firstName = firstName
        self.lastName = lastName
        self.career = career
    }
    init(firstName:String, lastName:String){
        self.firstName = firstName
        self.lastName = lastName
    }
    func fullName() ->String{
        return firstName + " " + lastName
    }
}
let person1 = Person(firstName: "aaa", lastName: "sss", career: "doctor")
let person2 = person1
person1 === person2
let person3 = Person(firstName: "aaa", lastName: "sss", career: "doctor")
person1 === person3
person1 !== person3

//什么時候使用類,什么時候使用結(jié)構(gòu)體

/*
1.一般位置堂竟,坐標(biāo)出嘹,溫度等等用結(jié)構(gòu)體。人疚漆,動物娶聘,車丸升,商店等等用類
2.類是引用類型狡耻,可以被繼承。結(jié)構(gòu)體是值類型
3.結(jié)構(gòu)體比類更“輕量級”

*/

類的繼承

class Avatar{
    var name: String
    var life = 100{
        didSet{
            if self.life <= 0{
                self.isAlive = false
            }
            if self.life > 100{
                self.life = 100
            }
        }
    }
    var isAlive: Bool = true
    var description: String{
        return "I'm avatar \(name)"
    }
    //指定構(gòu)造函數(shù)
    init(name : String){
        self.name = name
    }
    
    convenience init(firstName: String, lastName: String){
        self.init(name: firstName + " " + lastName)
    }
    
    func beAttacked(attack: Int) {
        life -= attack
        if life <= 0 {
            isAlive = false
        }
    }
}
class User:Avatar{
    var score = 0
    var level = 0
    //重載---重寫父類的方法/屬性
    override var description: String{
        return "I'm user \(name)"
    }
    //兩段式構(gòu)造
    var group: String
    init(name: String,group: String = "" ) {
        //1.構(gòu)造初值
        self.group = group
        super.init(name: name)
        //2.進(jìn)一步完善
        if group == ""{
            self.getScore(-10)
        }
    }
    //convenience便利構(gòu)造函數(shù)---沒有最終把整個對象構(gòu)造出來岭皂,而是執(zhí)行了一些邏輯之后爷绘,把構(gòu)造的任務(wù)交給了它本身的另外一個構(gòu)造函數(shù)
    //與之相對應(yīng)的就是指定構(gòu)造函數(shù)designated
    convenience init(group: String = ""){
        let name = User.generateUserName()
        self.init(name: name, group: group)
    }
    /*
     子類構(gòu)造函數(shù)
     1.如果子類沒有實現(xiàn)任何父類的指定構(gòu)造函數(shù)进倍,則自動繼承父類的所有指定構(gòu)造函數(shù)
     2.如果子類實現(xiàn)了父類的所有的指定構(gòu)造函數(shù),則自動繼承父類的所有便利構(gòu)造函數(shù)
     */
    override convenience init(name: String) {
        self.init(name: name, group: "")
    }
    
    func getScore(score: Int) {
        self.score += score
        if  score > level*100 {
            level += 1
        }
    }
    static func generateUserName() -> String{
        return "Player" + String(rand()%1_000_000)
    }
}
final class Magician: User {
    var magic = 0
    override var description: String{
        return "I'm magician \(name)"
    }
    override init(name: String, group: String) {
        let defaultGroups = ["Gryffindor","Hufflrpuff","Ravenclaw","Slytherin"]
        for theGroup in defaultGroups {
            if group == theGroup {
                super.init(name: name, group: group)
                return
            }
        }
        let group = defaultGroups[random()%4]
        super.init(name: name, group: group)
    }
    func heal(user: User) {
        user.life += 10
    }
}
final class Warrior: User {
    var  weapon: String
    init(name: String, group: String, weapon: String ) {
        self.weapon = weapon
        super.init(name: name, group: group)
    }
    override var description: String{
        return "I'm Warrior \(name)"
    }
    override func beAttacked(attack: Int) {
        self.life -= attack/2
    }
}
class Monster: Avatar {
    override var description: String{
        return "I'm monster \(name)"
    }
    func attack(user: User, amount: Int) {
        user.beAttacked(amount)
    }
}
final class Zombie: Monster{
    var  type = "Default"
    override var description: String{
        return "I'm zombie \(name)"
    }
}

let player = User(name: "aaa")
player.name
player.life
player.isAlive
player.score
player.beAttacked(10)
player.life
player.getScore(30)
player.level
//不希望再有子類垂蜗,在前面加final
//類的多態(tài)
let player1 = Magician(name: "Harry Potter")
let player2 = Warrior(name: "liuyubobobo")
let zombie = Zombie(name: "default zombie1")
let monster = Monster(name: "monster")

func printBasicInfo(avatar:Avatar) {
    print("The avatar's name is \(avatar.name)")
    print("The life is \(avatar.life). He is \( (avatar.isAlive) ? "still alive" : "dead")" )
    print("======")
}
printBasicInfo(player1)
printBasicInfo(player2)
printBasicInfo(zombie)
printBasicInfo(monster)

let avatarArr:[Avatar] = [player1, player2, zombie, monster]
for avatar in avatarArr{
    //avatar.life -= 10
    print(avatar.description)
}

player1.heal(player2)
player1.heal(player1)

//print(player1.description)
//print(player2.description)
//print(zombie.description)
//print(monster.description)

monster.attack(player1, amount: 20)
player1.life
monster.attack(player2, amount: 20)
player2.life

兩段式構(gòu)造

let user = User(name: "aaa", group: "ddd")
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末毅否,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子徘溢,更是在濱河造成了極大的恐慌然爆,老刑警劉巖奴烙,帶你破解...
    沈念sama閱讀 210,914評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件切诀,死亡現(xiàn)場離奇詭異幅虑,居然都是意外死亡倒庵,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,935評論 2 383
  • 文/潘曉璐 我一進(jìn)店門郁妈,熙熙樓的掌柜王于貴愁眉苦臉地迎上來噩咪,“玉大人剧腻,你說我怎么就攤上這事书在。” “怎么了拆又?”我有些...
    開封第一講書人閱讀 156,531評論 0 345
  • 文/不壞的土叔 我叫張陵儒旬,是天一觀的道長。 經(jīng)常有香客問我帖族,道長栈源,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,309評論 1 282
  • 正文 為了忘掉前任竖般,我火速辦了婚禮甚垦,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘涣雕。我一直安慰自己艰亮,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 65,381評論 5 384
  • 文/花漫 我一把揭開白布挣郭。 她就那樣靜靜地躺著迄埃,像睡著了一般侄非。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,730評論 1 289
  • 那天窥翩,我揣著相機與錄音仗岸,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛俯邓,可吹牛的內(nèi)容都是我干的朦蕴。 我是一名探鬼主播,決...
    沈念sama閱讀 38,882評論 3 404
  • 文/蒼蘭香墨 我猛地睜開眼嘱支,長吁一口氣:“原來是場噩夢啊……” “哼汛聚!你這毒婦竟也來了叹哭?” 一聲冷哼從身側(cè)響起舵稠,我...
    開封第一講書人閱讀 37,643評論 0 266
  • 序言:老撾萬榮一對情侶失蹤落追,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體烈菌,經(jīng)...
    沈念sama閱讀 44,095評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡妹卿,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,448評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了锅很。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片饶火。...
    茶點故事閱讀 38,566評論 1 339
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情堰酿,我是刑警寧澤顺饮,帶...
    沈念sama閱讀 34,253評論 4 328
  • 正文 年R本政府宣布,位于F島的核電站新翎,受9級特大地震影響岭埠,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,829評論 3 312
  • 文/蒙蒙 一泳秀、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦掰盘、人聲如沸叨橱。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,715評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至娇哆,卻和暖如春蒙秒,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,945評論 1 264
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留骂删,地道東北人。 一個月前我還...
    沈念sama閱讀 46,248評論 2 360
  • 正文 我出身青樓涌庭,卻偏偏與公主長得像芥被,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子脾猛,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,440評論 2 348

推薦閱讀更多精彩內(nèi)容