【发布时间】:2018-12-28 17:56:26
【问题描述】:
根据标题。
由于需要 init(a:),我无法初始化 'b',除非我采用上述重载方法。
问题(1):
有没有更好的方法来解决这个问题? self.b=0 必须包含在其中。
class BaseClass {
var a: Int
required init(a: Int) {
self.a = a
}
}
class SubClass: BaseClass {
var b: Int
init(b: Int, a: Int){
self.b = b
super.init(a: a)
}
required init(a: Int) {
self.b = 0 // have to put something here, otherwise complain
super.init(a: a)
}
}
然后,调用,例如:
let mySubClass = SubClass(b:2, a:3) //works by calling init(b:a:)
注意:另一种解决方法是在 required init 中使用 fatal error(但同样,它看起来不太对劲):
required init(a: Int) {
// fatal error()
}
此外,这让我想到了下一个问题,关于下面的示例。
问题(2):
存在协议,例如:
protocol RandomProtocol {
init(randomProp: Int)
}
调用例如:
let mySubClassWithProtocol = SubClassWithProtocol(c: 1, a: 2, b: 3) //works ok
有没有更好的方法来实现这个?再次,像上面一样,这似乎有点令人费解和违反直觉
SubClassWithProtocol需要从RandomProtocol和SubClass实现required init:
class SubClassWithProtocol: SubClass, RandomProtocol {
var c: Int
init(c: Int, a: Int, b: Int, randomProp: Int) {
self.c = c
super.init(b: b, a: a)
}
required init(a: Int) {
self.c = 0
super.init(a: a)
}
required init(randomProp: Int) {
//need to call self.c and super.init, otherwise complain
self.c = 0
super.init(b: 0, a: 0)
}
注意:
刚刚开始使用 Swift。试图找出我的方式。我理解上面的问题可能比实际更学术。但感谢您的帮助。
【问题讨论】:
-
var b: Int?
-
澄清问题:有没有更好的方法来编写更简单、更简洁的代码,而不是不得不声明 3 种不同类型的初始化程序(例如在 SubClassWithProtocol 中)?
-
这将如何让您更好地学习 Swift?大多数情况下,在为现实世界的情况设计类时,需要如何初始化属性是很自然的,并且您为这些情况编写 init 方法,尝试解决不存在的问题是您不应该做的事情。
标签: swift protocols swift4 subclass initializer