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也改变了---他们指向的是同一块内存空间(结构体是值类型,指向不同的内存空间,改变一个不会影响另一个)
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"//person1的let类型不会限制内存空间中career的类型,但是person1已经指向了一块内存空间,而且是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")

结构体和枚举是值类型,改变自身要加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

//什么时候使用类,什么时候使用结构体

/*
1.一般位置,坐标,温度等等用结构体。人,动物,车,商店等等用类
2.类是引用类型,可以被继承。结构体是值类型
3.结构体比类更“轻量级”

*/

类的继承

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)"
    }
    //指定构造函数
    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)"
    }
    //两段式构造
    var group: String
    init(name: String,group: String = "" ) {
        //1.构造初值
        self.group = group
        super.init(name: name)
        //2.进一步完善
        if group == ""{
            self.getScore(-10)
        }
    }
    //convenience便利构造函数---没有最终把整个对象构造出来,而是执行了一些逻辑之后,把构造的任务交给了它本身的另外一个构造函数
    //与之相对应的就是指定构造函数designated
    convenience init(group: String = ""){
        let name = User.generateUserName()
        self.init(name: name, group: group)
    }
    /*
     子类构造函数
     1.如果子类没有实现任何父类的指定构造函数,则自动继承父类的所有指定构造函数
     2.如果子类实现了父类的所有的指定构造函数,则自动继承父类的所有便利构造函数
     */
    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
//类的多态
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

两段式构造

let user = User(name: "aaa", group: "ddd")
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,948评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,371评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,490评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,521评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,627评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,842评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,997评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,741评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,203评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,534评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,673评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,339评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,955评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,770评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,000评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,394评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,562评论 2 349

推荐阅读更多精彩内容