我有两节课,Shape和Square
class Shape {
var numberOfSides = 0
var name: String
init(name:String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
class Square: Shape {
var sideLength: Double
init(sideLength:Double, name:String) {
super.init(name:name) // Error here
self.sideLength = sideLength
numberOfSides = 4
}
func area () -> Double {
return sideLength * sideLength
}
}
Run Code Online (Sandbox Code Playgroud)
通过上面的实现,我得到错误:
property 'self.sideLength' not initialized at super.init call
super.init(name:name)
Run Code Online (Sandbox Code Playgroud)
为什么我必须self.sideLength在打电话前设置super.init?
我无法将init方法添加到以下UIViewController类.我需要在init方法中编写一些代码.我必须编写init(编码器)方法吗?即使我添加编码器和解码器方法,我仍然会遇到错误.我也尝试使用没有任何参数的init方法,但这似乎也不起作用.
class ViewController: UIViewController {
var tap: UITapGestureRecognizer?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nil, bundle: nil)
tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
}
...
...
}
Run Code Online (Sandbox Code Playgroud)
如果我调用不带参数的super.init()方法,则错误为"必须调用超类的指定初始化程序",如果我传递参数nib和bundle,则错误为"必需的初始化程序初始化程序(编码器)".
即使我添加init(编码器)和init(解码器)它也不起作用.