【问题标题】:Swift - How to initialize property in subclass when there is a required initializer to be satisfied?Swift - 当需要满足所需的初始化程序时如何初始化子类中的属性?
【发布时间】: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需要从RandomProtocolSubClass实现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


【解决方案1】:

除了必须在初始化程序中设置默认值之外,还有其他方法来初始化属性吗?是的,有-

  • 您可以将 b 设为可选 - var b: Int?

  • 您可以将 b 设为隐式展开的可选 - var b: Int!

  • 您可以在声明时为 b 设置默认值 - var b: Int = 0

这些方法将使您不必在初始化程序中调用 self.b = 0,但正如 Joakim 在现实世界中指出的那样,您使用哪种方法取决于您的情况。

【讨论】:

  • 感谢您的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-26
  • 2020-03-05
  • 2019-11-23
相关资源
最近更新 更多