接口和类方法中的Self
作者:
盖小聂 | 来源:发表于
2019-06-28 16:48 被阅读0次protocol Copyable {
//Self不仅指代实现该接口的类型本身,也包括了这个类型的子类。
func copy() -> Self
}
class MyClass: Copyable {
var num = 1
func copy() -> Self {
let result = type(of: self).init()
result.num = num
return result
}
required init() {
//如果需要构建一个Self类型的对象的话,需要有required关键字修饰的初始化方法,这是因为Swift必须保证当前类和其子类都能响应这个init方法。
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let object = MyClass()
object.num = 100
let newObject = object.copy()
newObject.num = 1
print(object.num) //100
print(newObject.num) //1
}
}
本文标题:接口和类方法中的Self
本文链接:https://www.haomeiwen.com/subject/yesecctx.html
网友评论