swift - Swift 错误代码:实例成员 'getStory' 不能用于类型 'StoryBrain';你的意思是使用这种类型的值吗?
问题描述
无法弄清楚如何处理这个快速错误代码......我需要创建一个实例还是使其成为静态?
struct Story{
var storyTitle : String
var choice1 : String
var choice2 : String
init(t: String,c1: String, c2: String ) {
storyTitle = t
choice1 = c1
choice2 = c2
} }
struct StoryBrain{
var storyNumber = 0
let stories = [
Story(t: "You see a fork in the road", c1: "Take a left", c2: "Take a right"),
Story(t: "You see a tiger", c1: "Shout for help", c2: "Play dead"),
Story(t: "You find a treasure chest", c1: "Open it", c2: "Check for traps")
]
func getStory() -> String{
return stories[storyNumber].storyTitle
}
mutating func nextStory(userChoice: String) {
if storyNumber + 1 < stories.count{
storyNumber += 1
} else {
storyNumber = 0
}
}
}
func updateUI(){ storyLabel.text = StoryBrain.getStory()}
解决方案
问题在这里:
StoryBrain.getStory()
^ Instance member 'getStory' cannot be used on type 'StoryBrain'
如错误所示,是一个实例getStory
方法,这意味着您只能在. 以下是其他一些建议:StoryBrain
struct StoryBrain {
// Make private by default
private let stories = [...]
private var storyNumber = 0
// Make a computed property
var currentStoryTitle: String {
stories[storyNumber].storyTitle
}
// Make the name imperative; reflects that this is a mutating function
// Also don't need mutating anymore since this is a class
func advanceStory(...) {
...
}
}
如果您初始化此对象,例如let brain = StoryBrain()
,那么您可以使用实例成员 likeadvanceStory
和currentStoryTitle
on brain
。您将要创建此对象/将其存储在您所在的任何类updateUI
中。如果您从几个不同的地方使用同一个大脑,那么您可能想要使用单例模式,您可以在对此的原始编辑中看到回答。
推荐阅读
- python - Python3.9 datetime.py 中的语法错误
- javascript - Outlook 加载项无法重置密件抄送字段
- ios - 使用 Swift Result 类型设置 XCTest 时出错
- c++ - C++ 指针和 C 风格的数组初始化
- npm - 如何安装 安装依赖项 对于 Codrops 中的演示
- reactjs - 我们是否应该在 UseEffect 中将函数作为依赖项传递
- audio - MediaCapture 中是否有降噪方法?
- python - 如何编写脚本从快捷方式运行 2 个 CMD 实例和(Win 10)中的 2 个 python 程序?
- bash - 我可以对 BASH 中的条件使用多个 AND (&&) 运算符吗
- python - Python 的子进程在使用 PIPE 读取很长的输出时返回截断的输出