Swift继承(Inheritance)
来源:互联网 发布:wince5.0 盘点软件 编辑:程序博客网 时间:2024/06/05 11:16
玩过其他开发语言的小伙伴都知道继承,也就是子类继承父类的特性。这在开发过程中非常有用,可以节省大量工作量。
声明基类
下面我们声明一个常见的基类Base,有两个属性(count、description)和一个方法(inherited),其中description是只读的。
/// 基类class Base { var count = 0.0 var description: String { return "count:\(count)" } // MARK: 可继承 func inherited() { }}
子类化
子类继承基类很简单,声明如下,子类和父类间用“:”隔开,如果有多个父类,父类间用“,”隔开。
/// 子类class Subclass: Base {}
重写
在子类中可以实现父类的所有特性,但是有的时候我们想扩展属性或方法。这个时候就需要用到关键字Overriding。
下面让子类重写父类的属性和方法。
class Subclass: Base { // 继承的属性和方法前都有override override var count:Double { didSet { print("\(__FUNCTION__)") } } override var description: String { return "\(__FUNCTION__)" + super.description } override func inherited() { print("\(__FUNCTION__)") }}
可以在属性和方法前使用override,表示这个属性和方法是继承了父类。如果想调用父类的属性或方法,只需要使用super后面跟你想使用的属性和方法。你可以理解为self代表当前类,super代表父类。
防止重写
有的时候我们不希望其他人通过继承改写我们的特性,希望它是不可重写的。这里可以使用关键字final,如下所示:
- final var/let:防止常量或变量被重写;
- final func:防止实例方法被重写;
- final class func:防止类型方法被重写;
- final subscript:防止下标方法被重写;
- final class:防止当前类被继承。
这里以实例方法举例,在Base中添加如下方法:
final func preventing() { // 如果不想子类继承,可在类、属性或方法前添加final}
则子类Subclass不可重写此方法。
其他
参考资料
The Swift Programming Language (Swift 2.1)
文档修改记录
版权所有:http://blog.csdn.net/y550918116j
0 0
- Swift继承(Inheritance)
- Swift 继承Inheritance
- Swift 继承(Inheritance)
- 对照Java学习Swift--继承(Inheritance)
- 继承 Inheritance
- inheritance(继承)
- Inheritance(继承)
- Inheritance继承
- Inheritance继承
- Swift学习笔记13——类继承(Inheritance)
- Swift编程语言学习14——Swift中如何使用继承(Inheritance)
- Swift 学习笔记---Inheritance
- 继承映射(Inheritance Mappings)
- 继承(Inheritance)
- 单继承(single inheritance)
- 继承(inheritance)语法
- 要点Java13 继承Inheritance
- 继承(Inheritance)
- 拼装当前网页的相对路径
- 构建乘积数组(利用辅助空间+剑指offer)
- spring DelegatingFilterProxy 过滤器 的原理及运用
- XMPP 服务器 Openfire 的 Emoji 支持问题(进行部分修改)
- Linux系统内存监控全面讲解:free命令
- Swift继承(Inheritance)
- 这个该从什么写起啊
- 【已解决】Ubuntu输入密码后无法登陆闪屏问题
- 带图片的Toast提示信息框
- ubuntu下设置网络
- Xcode7 上传报错
- CF 460B Little Dima and Equation
- Linux关机命令详解
- OC学习 第二章便利初始化 便利构造器 getter/setter方法