iOS经典讲解之Swift枚举(Enum)、协议(protocol)、扩展(Extension)

来源:互联网 发布:淘宝卖家发货货到付款 编辑:程序博客网 时间:2024/06/05 02:31

作者:Loving_iOS

转载请标明出处:http://blog.csdn.net/loving_ios/article/details/49406865

本次开发环境为Xcode7.0.1 创建playground文件 进行的代码编写。

//**********************枚举**************************//enum 枚举名:类型 {//    //    case 分支1 = 赋值1//    case 分支2 = 赋值2//    //}enum PersonIndetity:String {    case Teacher = "Teacher_id"    case Student = "Student_id"}// 类class Person {        var indeitity:PersonIndetity    var name:String    var age:String        // 类的构造器    init(name:String, age:String, idd:PersonIndetity) {        self.indeitity = idd        self.name = name        self.age = age    }        func hello() {        print("hello")    }    // 类方法    class func hello2() {            }    }// 枚举 枚举名.类型 其中枚举名可以省略var person = Person(name: "Tom", age: "30", idd: PersonIndetity.Student)// 枚举值得获取// 获取当前分支person.indeitity.hashValue// 获得分区的值person.indeitity.rawValue// 继承 类名:父类名class Student:Person {        // 子类的属性    var classNumber:Int = 23    init(name: String, age: String, idd: PersonIndetity, classNumber:Int) {                // 如果属性仅指定类型 需要在super.init之前进行赋值操作        super.init(name: name, age: age, idd: idd)        self.classNumber = classNumber            }        // 重写父类方法 需要使用override关键字    override func hello() {            }  override class func hello2() {        }    }// 协议protocol OneProtocol {        func typeFunc()    static func typeFunc2()    mutating func typeFunc3()    }// 类和结构体实现协议方法的时候 需要根据本身的语法规则做出调整class newStudent:OneProtocol {        func typeFunc() {            }    class func typeFunc2() {            }       func typeFunc3() {            }}struct VideoNew:OneProtocol {        func typeFunc() {            }    static func typeFunc2() {            }   mutating func typeFunc3() {            }}// 类同时继承父类和协议的时候 父类必须写在前面//class StudentNew:Person, OneProtocol {//    //}@objc protocol SecondProtocol {    optional func hello()}// 注意:当协议中方法使用optional 声明可选方法时 协议必须声明成@objc 此时的协议为类协议 不能被结构体继承// 扩展var value:String = ""extension Person {        func helloworld() {            }        // 如果想扩展属性 只能是计算属性    var stu:String {        get{                        return value        }        set {            value = newValue        }    }        // 扩展构造器需要使用convenience    convenience init(name:String, age:String, idd:PersonIndetity, stu:String) {        self.init(name:name, age:age, idd:idd)        self.stu = stu    }}var person_one = Person(name: "Tom", age: "20", idd: PersonIndetity.Student, stu: "帅哥")person_one.stuperson_one.stu = "靓妹"person_one.stu
1 0
原创粉丝点击