这个继承关系类的具体实现代码如下:
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] for item in people { if let student = item as? Student { print("Student school: \(Student.school)") } else if let worker = item as? Worker { print("Worker factory: \(Worker.factory)") } }操作符在转换的同时进行隐式拆包。
示例代码如下:... let people = [student1, student2, student3, worker1, worker2] ... let stud1 = people[0] as? Student //people数组的第一个元素 print(stud1) print(stud1!.name) let stud2 = people[1] as! Student //people数组的第二个元素 print(stud2) print(stud2.name)
顶 0 踩 0
我的同类文章
猜你在找
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
智捷iOS课堂 智捷iOS课堂-大量免费iOS视频-
大家一起学习探讨 技术讨论群cocos2d-x群:257760386;iOS学习讨论qq群:286411514/204462948 技术讨论论坛
个人资料
tonny_guan
积分:12393
我的课程 更多
Cocos2d-x实战-手...
难度:高级
类型:实战教学Part 5:Cocos2...
难度:中级
类型:技术教程Part 4:Cocos2...
难度:中级
类型:技术教程文章搜索
博客专栏
Cocos2d-x实战
文章:78篇
阅读:193373iOS经典应用剖析
文章:10篇
阅读:19237iOS开发那些事
文章:54篇
阅读:234880我的新浪微博