【问题标题】:Swift Error Code: Instance member 'getStory' cannot be used on type 'StoryBrain'; did you mean to use a value of this type instead?Swift 错误代码:实例成员 'getStory' 不能用于类型 'StoryBrain';你的意思是使用这种类型的值吗?
【发布时间】:2021-11-25 22:07:31
【问题描述】:

无法弄清楚如何处理这个快速错误代码...我需要创建一个实例还是使其成为静态??

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
    }
}



}

函数更新UI(){ storyLabel.text = StoryBrain.getStory()}

【问题讨论】:

    标签: swift xcode


    【解决方案1】:

    我猜你正在 Udemy 上参加 Angelas “iOS 和 Swift - 完整的 iOS 应用程序开发训练营”课程。

    在 ViewController 内部,创建一个 var:

    class ViewController: UIViewController {
    var storyBrain = StoryBrain()
    @IBOutlet weak var storyLabel: UILabel! }
    

    这使您可以利用您的 StoryBrain 模型。祝你好运!

    【讨论】:

      【解决方案2】:

      问题就在这里:

      StoryBrain.getStory()
                ^ Instance member 'getStory' cannot be used on type 'StoryBrain'
      

      如错误所示,getStory 是一个实例方法,这意味着您只能在StoryBraininstances 上调用它。以下是一些其他建议:

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

      【讨论】:

      • 我想在这里添加几件事。除非您绝对必须,否则我不会使用单例。当您在整个应用程序的生命周期中需要单个实例时,单例很有用,但它们会引入难以管理的全局状态并可能导致错误。因此,如果您不需要单例,只需创建一个实例即可。另外,还有一个建议。当你创建一个单例时,你需要一个私有的初始化器,否则调用者仍然可以创建一个普通的实例!最好添加一个私有的 init() {} 来解决这个问题。
      • @JKoko 好点。尽管私有初始化器很常见,但 Swift API 中的许多带有单例的类都没有私有初始化器。鉴于名称中的“大脑”,我认为这是全球应用程序状态的核心。如果不是,我同意你的观点,一个简单的实例更好。
      • 我更新了使用实例的答案。如果操作人员发现他们将此对象用作其应用中的通用事实来源,他们可以查看编辑历史记录。
      猜你喜欢
      • 2021-06-29
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多