gpt4 book ai didi

Swift 常量连接变量来定义 if 语句

转载 作者:行者123 更新时间:2023-11-30 10:48:49 26 4
gpt4 key购买 nike

我完成了创建一个故事应用程序的挑战,该应用程序根据您给出的答案具有不同的结局。该应用程序运行良好,但我并没有真正完全理解它。基本上它非常简单,只有一个带有文本的 UILabel 和 2 个可以改变游戏每一步的 UIButton。

为了将 if 语句与其他语句分开,我们必须创建一个名为 storyIndex 的变量,并将其放在 sender.tag == 之后。

代码如下:

@IBAction func buttonPressed(_ sender: UIButton) {

if sender.tag == 1 && storyIndex == 1 {

storyTextView.text = story3
topButton.setTitle(answer3a, for: .normal)
bottomButton.setTitle(answer3b, for: .normal)
storyIndex = 3

}

else if sender.tag == 2 && storyIndex == 1 {

storyTextView.text = story2
topButton.setTitle(answer2a, for: .normal)
bottomButton.setTitle(answer2b, for: .normal)
storyIndex = 2
}

else if sender.tag == 1 && storyIndex == 3 {

storyTextView.text = story6
storyIndex = 6
topButton.isHidden = true
bottomButton.isHidden = true
}

else if sender.tag == 2 && storyIndex == 3 {
storyTextView.text = story5
storyIndex = 5
topButton.isHidden = true
bottomButton.isHidden = true

}

else if sender.tag == 1 && storyIndex == 2 {

storyTextView.text = story3
topButton.setTitle(answer3a, for: .normal)
bottomButton.setTitle(answer3b, for: .normal)
storyIndex = 3
}

else if sender.tag == 2 && storyIndex == 2 {

storyTextView.text = story4
storyIndex = 4
topButton.isHidden = true
bottomButton.isHidden = true
}

并且该变量被放置在 IBoutlets 连接下方:

var storyIndex : Int = 1

在类下方的代码顶部,我们有包含故事文本的常量:

例如:

let story1 = "Your car has blown a tire on a winding road in the middle of nowhere with no cell phone reception. You decide to hitchhike. A rusty pickup truck rumbles to a stop next to you. A man with a wide brimmed hat with soulless eyes opens the passenger door for you and asks: \"Need a ride, boy?\"."

所以我终于在“问答”选项卡的帮助下弄清楚了如何做到这一点,但实际上我不明白 Swift 如何知道 storyIndex 让我们说 2 是一个故事 2 ?我在哪里定义它,基本上是常量和变量storyIndex之间的联系。 Index 这个词的作用是这样吗?还是我定义的?

做这样的事情不是更容易吗?

if sender.tag == 1 && storyTextView.text == (\story1) {

抱歉我的英语,这是我的第三语言。

最佳答案

您发布的代码只是在按下按钮时运行。该按钮是根据 InterfaceBuilder 中设置的 tag 属性确定的。看起来操作 1 是 tag = 1 的上一个操作,而操作 2 是 tag = 2 的下一个操作。

然后,代码查看当前故事索引和按下的按钮(标签),并确定下一个故事索引是什么并设置适当的故事文本。

它不比较故事文本的原因是故事文本并不能真正为您提供一种简单的方法来了解您在故事中的位置,除非您阅读文本。此外,比较字符串比比较整数花费的时间更长,尽管在这种情况下可以忽略不计。

这里,索引和故事文本之间的映射是在每个 if 语句内完成的。更好的方法是使用一个数组,其中包含按故事索引索引的故事文本(例如:storyText[storyIndex])。

关于Swift 常量连接变量来定义 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55107880/

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