OC转Swift之基础篇(三)--类

本文深入探讨Swift中的类,包括属性定义、构造器、方法、类属性、实例方法和类方法。通过示例代码展示了如何定义和使用类,如Person类、Account类以及Record类,还涉及到类的继承和方法重写。通过对类的不同方面进行实践,有助于理解Swift的面向对象编程。

//类

//属性定义(get,set方法)、便利构造器方法、方法定义

class Person {

    var firstName =""

    var lastName =""

    var age =0

    var fullName:String{//属性的get、set方法

        get{

            returnfirstName+" "+lastName

        }

        set{

            let array =fullName.components(separatedBy:" ")

            if array.count >=2 {

                firstName = array.first!

                lastName =fullName.substring(from: (firstName+" ").endIndex)

            }else{

                firstName =""

                lastName =fullName

            }

        }

    }

    lazyvar account =Account()//懒加载类(类的属性必须为var)

    init(firstName:String,lastName:String,age:Int) {//指定便利构造器方法(-(instancetype)initWithFirst:(NSString *)firstName...)

        self.firstName = firstName

        self.lastName = lastName

        self.age = age

    }

    convenienceinit(fullName:String) {//便利构造方法

        let array = fullName.components(separatedBy:" ")

        if array.count >=2 {

           let first = array.first!

           let last = fullName.substring(from: (first+" ").endIndex)

           self.init(firstName:first,lastName:last,age:0)

        }else{

           self.init(firstName:"",lastName:fullName,age:0)

        }

    }

    func modifyInfoWithAge(firstName:String,lastName:String,age:Int) {//实例方法

        self.firstName = firstName

        self.lastName = lastName

        self.age = age

    }

    staticvar skin:Array<String> {//类属性

        return ["yellow","white","blace"]

    }

    func showMessage() {//实例方法

        print("MyName is\(fullName),firstName is\(firstName),lastName is\(lastName),age is\(age).")

    }

    classfunc showClassName(){//类方法

        print("ClassName is \"\(self)\"")

    }

    deinit {//析构方法(无法直接调用)

        print("deinit...")

    }

}

//类里面属性的值改变是监听

class Account {

    var balance:Double =0.0{

        willSet{

            self.balance =2.0

            print("Account.balance willSet,newValue=\(newValue),value=\(self.balance)")

        }

        didSet{

            self.balance =3.0

            print("Account.balance didSet,oldValue=\(oldValue),value=\(self.balance)")

        }

    }

}

//创建类

var p =Person.init(firstName:"Jonny", lastName: "Deng", age:25)

        p.account.balance =10 //属性设置

        p.showMessage( )//实例方法调用

        for colorinPerson.skin { //类属性调用

            print(color)

        }

        p = Person.init(fullName:"Jenny Yang")

        p.age =18

        p.showMessage()

        p.modifyInfoWithAge(firstName:"Jonny", lastName:"Deng", age:25)

        p.showMessage()

        Person.showClassName() //类方法调用

//类の下标索引

class Record {

    var store:[String:String]

    init(data:[String:String]) {

        self.store = data;

    }

    subscript(index:Int)->String{

        get{

            let key =self.store.keys.sorted()[index]

            returnself.store[key]!

        }

        set{

            let key =self.store.keys.sorted()[index]

            self.store[key] = newValue

            

        }

    }

    subscript(key:String)->String{

        get{

            returnstore[key]!

        }

        set{

            store[key] = newValue

        }

    }

}

let r =Record.init(data: ["name":"Jenny","sex":"gril"])

        print("r[0]=\(r[0])")//结果:r[0]=Jenny

        r["sex"] ="boy"

        print(r[1])//结果boy

//类の继承

class Student: Person {//Student类继承Person类

    overridevar firstName:String{ // 重写属性监听

        willSet{

            print("oldValue=\(firstName)")

        }

        didSet{

            print("newValue=\(firstName)")

        }

    }

    var score:Double 

//子类构造 初始化之后调用父类的构造方法

    init(firstName:String,lastName:String,score:Double) {

        self.score = score

        super.init(firstName: firstName, lastName: lastName, age:0)

    }

    convenienceinit() {

        self.init(firstName:"",lastName:"",score:0)

    }

//重写父类的方法

    overridefunc showMessage() {

        print("MyName is\(fullName),firstName is\(firstName),lastName is\(lastName),age is\(age),score is\(score).")

    }

}

var student =Student.init()

        student.firstName ="Jonny"

        student.lastName ="Deng"

        student.age =25

        student.score =99

        student.showMessage()

        

        student = Student.init(firstName:"Jenny", lastName:"Yang", score:59)

        student.age =18

        student.showMessage()


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值