如何通过Swift中的super.init从子类修改基类属性?
考虑Base类有一个名为first name的属性,所以我希望子类添加姓氏并通过super.init传递它 以下是代码
class mainClass {
var firstname : String = "Abhinav"
init(firstname : String){
self.firstname = firstname
}
func printfirstname(){
print(firstname)
}
}
class subClass:mainClass {
var lastname : String
init(lastname:String){
self.lastname = lastname
let name :String = firstname + lastname
super.init(firstname:name)
}
func printname(){
print(firstname)
}
}
var subclass = subClass(lastname:"Jha")
subclass.printfirstname()
我收到错误" 使用' self'在财产访问'名字'在super.init初始化自我之前"
答案 0 :(得分:0)
您正在尝试在初始化之前访问超级类的firstName
。您应该先致电super.init()
。它看起来像是:
init(lastname:String){
self.lastname = lastname
super.init(firstname: "Abhinav")
let name = firstname + lastname
self.firstname = name
}