gpt4 book ai didi

swift - 为什么我的类变量不会更改为文本框的文本?

转载 作者:行者123 更新时间:2023-11-30 10:38:04 25 4
gpt4 key购买 nike

我正在编写一个简单的函数,旨在将一些文本框的内容写入类实例中的变量中。

当我尝试打印文本框的内容时,它起作用了。内容就在那里。

我尝试将文本框连接到运行该函数的按钮。

以下是一些父类和子类:

class RapName {
var numberProper: String
var nameProper: String
...

init(){
self.numberProper = "number proper"
self.nameProper = "name proper"
...
}
}

class rapNameStyle: RapName {

var twoChainzStyle: (String, String, String)?
var tinyTimTheRapperStyle: (String, String, String, String, String)?
...
var allStyles: [Any]?


override init (){
super.init()
self.twoChainzStyle = (numberProper, " ", noun)
self.tinyTimTheRapperStyle = (adjective, " ", nameProper, " the ", noun)
...
self.allStyles = [twoChainzStyle!, bigSnitchStyle!, crunchyBlackStyle!, tinyTimTheRapperStyle! as Any, zaeTheBlacksmithStyle!,
littleRichardStyle!,drDreStyle!, poetPeteStyle!, notoriousBIGStyle!, flavaFlavStyle!, mrHappyStyle!, captainPotatoStyle!, stevensShakinStyle!] as [Any]
}

}

这是函数:

@IBAction func buttonPress(_ sender: Any) {
rapName.nameProper = textBox1.text!
rapName.numberProper = textBox2.text!
rapName.verb = allVerbs.randomElement()!
rapName.noun = allNouns.randomElement()!
rapName.adjective = allAdjectives.randomElement()!
rapName.secondAdjective = allAdjectives.randomElement()!
rapName.secondNoun = allNouns.randomElement()!
rapName.acronym = textBox4.text!
rapName.titleProper = textBox3.text!

let randomStyle = rapName.allStyles?.randomElement()
let finalString = String("\(randomStyle)")
...
rapNameLabel.text = finalString
}
}

目标是显示具有随机样式的说唱名称,其中包含文本框的内容。

但是,仅返回随机说唱名称样式中的原始初始化变量。

因此,例如,如果形容词的文本框包含“little”,并且名称正确的文本框包含“wiggles”,并且选择了随机样式littlerichardstyle,则标签应显示“little wiggles”,而不是只显示“形容词” “名称正确”(来自初始化程序)。

非常感谢

最佳答案

您应该将 RapNameStyle 中的所有 var 设为计算属性:

class RapNameStyle: RapName {
var twoChainzStyle: (String, String, String)? {
return (numberProper, " ", noun)
}
var tinyTimTheRapperStyle: (String, String, String, String, String)? {
return (adjective, " ", nameProper, " the ", noun)
}
// Same for others
var allStyles: [Any]? {
return [twoChainzStyle!, bigSnitchStyle!, crunchyBlackStyle!, tinyTimTheRapperStyle! as Any, zaeTheBlacksmithStyle!,
littleRichardStyle!,drDreStyle!, poetPeteStyle!, notoriousBIGStyle!, flavaFlavStyle!, mrHappyStyle!, captainPotatoStyle!, stevensShakinStyle!]
}
}

那么 init() 就是 super.init()

考虑以下非常简单的示例:

class ASuper {
var top: Int

init() {
top = 1
}
}

class BSub: ASuper {
var under: Int?
var all: [Any]?

override init() {
super.init()
self.under = 10
self.all = [under!]
}

}

let b = BSub()
b.under = 200

print(b.all!)

您得到 [10] 而不是 [200]当你将 b.under 的值更改为 200 时,all 不会重新计算,它仍然是 [10]。它将带有计算出的变量。

关于swift - 为什么我的类变量不会更改为文本框的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57480444/

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