首页 > 解决方案 > 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()}

标签: swiftxcode

解决方案


问题在这里:

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(),那么您可以使用实例成员 likeadvanceStorycurrentStoryTitleon brain。您将要创建此对象/将其存储在您所在的任何类updateUI中。如果您从几个不同的地方使用同一个大脑,那么您可能想要使用单例模式,您可以在对此的原始编辑中看到回答。


推荐阅读