标签:swift swift教程 swift视频 ios ios8
继承会发生在子类和父类中,如图所示,是一系列类的继承关系类图,Person是类层次结构中的根类,Student是Person的直接子类,Worker是Person的直接子类。class Person { var name : String var age : Int func description() -> String { return "\(name) 年龄是: \(age)" } convenience init () { self.init(name: "Tony") self.age = 18 } convenience init (name : String) { self.init(name: name, age: 18) } init (name : String, age : Int) { self.name = name self.age = age } } class Student : Person { var school : String init (name : String, age : Int, school : String) { self.school = school super.init(name : name, age : age) } } class Worker : Person { var factory : String init (name : String, age : Int, factory : String) { self.factory = factory super.init(name : name, age : age) } }
let Student1 = Student(name : "Tom", age : 18, school : "清华大学") ① let Student2 = Student(name : "Ben", age : 28, school : "北京大学") let Student3 = Student(name : "Tony", age : 38, school : "香港大学") ② let Worker1 = Worker(name : "Tom", age : 18, factory : "钢厂") ③ let Worker2 = Worker(name : "Ben", age : 20, factory : "电厂") ④ let people = [Student1, Student2, Student3, Worker1, Worker2] ⑤ var StudentCount = 0 var WorkerCount = 0 for item in people { ⑥ if item is Worker { ⑦ ++WorkerCount } else if item is Student { ⑧ ++StudentCount } } println("工人人数:\(WorkerCount) ,学生人数:\(StudentCount) 。")
let Student1 = Student(name : "Tom", age : 18, school : "清华大学") ① let Student2 = Student(name : "Ben", age : 28, school : "北京大学") let Student3 = Student(name : "Tony", age : 38, school : "香港大学") ② let Worker1 = Worker(name : "Tom", age : 18, factory : "钢厂") ③ let Worker2 = Worker(name : "Ben", age : 20, factory : "电厂") ④ let people = [Student1, Student2, Student3, Worker1, Worker2] ⑤ for item in people { ⑥ if let Student = item as? Student { ⑦ println("Student school: \(Student.school)") ⑧ } else if let Worker = item as? Worker { ⑨ println("Worker factory: \(Worker.factory)") ⑩ } }
let Student1 = Student(name : "Tom", age : 18, school : "清华大学") let Student2 = Student(name : "Ben", age : 28, school : "北京大学") let Student3 = Student(name : "Tony", age : 38, school : "香港大学") let Worker1 = Worker(name : "Tom", age : 18, factory : "钢厂") let Worker2 = Worker(name : "Ben", age : 20, factory : "电厂") let people1: [Person] = [Student1, Student2, Student3, Worker1, Worker2] ① let people2: [AnyObject] = [Student1, Student2, Student3, Worker1, Worker2] ② let people3: [Any] = [Student1, Student2, Student3, Worker1, Worker2] ③ for item in people3 { ④ if let Student = item as? Student { println("Student school: \(Student.school)") } else if let Worker = item as? Worker { println("Worker factory: \(Worker.factory)") } }
这3种类型的数组都可以成功放入5个实例,而且可以在第④行使用for Int循环遍历出来,其他的类型代码不再解释。
欢迎关注智捷iOS课堂微信公共平台
标签:swift swift教程 swift视频 ios ios8
原文地址:http://blog.csdn.net/tonny_guan/article/details/39057283