почему я получаю (self:), когда я делаю функцию? - PullRequest
0 голосов
/ 01 мая 2020
struct StoryBrain {
    var storyNumber = 0


    let Allstory = [
        Story(s: "There is a fork on the road", c1: "Take a left", c2: "Take a right"),
        Story(s: "There are two door", c1: "Enter the left door", c2: "Enter the Right door"),
        Story(s: "You can have either a dog or a cat", c1: "I will have a dog", c2: "I will have a cat")
    ]

    func getStory() ->String {
        return Allstory[storyNumber].mainStory
    }
    func getchoice1() -> String {
        return Allstory[storyNumber].choice1
    }
    func getchoice2() -> String {
        return Allstory[storyNumber].choice2
    }

Это модель

в контроллере представления, я хочу сделать функцию updateUI

func updateUI() {
    storyLabel.text = StoryBrain.getStory(self: StoryBrain)

Я не понимаю, почему я получаю (self: StoryBrain) вместо просто ().

Ответы [ 3 ]

1 голос
/ 01 мая 2020

Поскольку getStory() не помечено как static.

1 голос
/ 01 мая 2020

Это не stati c или методы класса ... вам нужно создать объект этого класса для вызова его функций сэр ... или сделать их статическими / функциями класса, если вы не хотите создавать объект этого класса

Либо сделайте

func updateUI() {
  let story = StoryBrain()
  storyLabel.text = story.getStory()
 }

Или вы можете использовать их c, но это не очень хороший подход

struct StoryBrain {
   static var storyNumber = 0


   static let Allstory = [
        Story(s: "There is a fork on the road", c1: "Take a left", c2: "Take a right"),
        Story(s: "There are two door", c1: "Enter the left door", c2: "Enter the Right door"),
        Story(s: "You can have either a dog or a cat", c1: "I will have a dog", c2: "I will have a cat")
    ]

   static func getStory() ->String {
        return Allstory[storyNumber].mainStory
    }
   static func getchoice1() -> String {
        return Allstory[storyNumber].choice1
    }
  static  func getchoice2() -> String {
        return Allstory[storyNumber].choice2
    }

Теперь вы можете сделать

func updateUI() {
    storyLabel.text = StoryBrain.getStory()
  }
0 голосов
/ 01 мая 2020

Вы объявляете getStory как метод экземпляра. Поэтому вам нужно вызвать его для экземпляра StoryBrain, это то, что компилятор пытается сообщить вам с помощью self.

let storyBrain = StoryBrain() // create an instance
storyLabel.text = storyBrain.getStory() // call the instance method on that instance
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...