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")

你可能感兴趣的:(类)