gpt4 book ai didi

swift - 在 Swift 中更改父类(super class)变量

转载 作者:搜寻专家 更新时间:2023-11-01 05:54:31 25 4
gpt4 key购买 nike

我在Apple提供的Swift文档中看到了这句话

“Subclasses are only allowed to modify variable properties of superclasses during initialization.”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.

但如果我运行这段代码,它就没有问题:

class Person{
var name:String

init(name:String){
self.name = name
}
}

class SuperHero:Person{
var power:String?

init(name:String, power:String?){
self.power = power
super.init(name: name)
}

func changeName (){
// HERE I'M CHANGING A SUPERCLASS VARIABLE outside Initialization!!!
self.name = "Mark"
}
}

let superman = SuperHero(name: "Superman", power: "Fly!")
superman.changeName()
println("\(superman.name)")

我是否误解了文档?

最佳答案

引用的句子中存在严重的误解。这是其自然环境中的原始报价。

Subclasses are only allowed to modify variable properties of superclasses during initialization. You can’t modify inherited constant properties of subclasses.

请读入正确的重音,因为这句话的意思是换句话说:

  1. 您可以在初始化期间修改父类(super class)的变量,但您不能对父类(super class)的常量做这样的事情。

  2. 这里没有这样的声明:您只能在初始化期间修改变量,但之后您将不允许修改它们。 p>

我希望现在说得通了。

关于swift - 在 Swift 中更改父类(super class)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24361548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com