Reputation: 1
Can't figure out how to go about this swift error code... Do I need to make an instance or make it static??
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()}
Upvotes: 0
Views: 882
Reputation: 11
I guess your doing Angelas "iOS & Swift - The Complete iOS App Development Bootcamp" course on Udemy.
Inside the ViewController, create a var:
class ViewController: UIViewController {
var storyBrain = StoryBrain()
@IBOutlet weak var storyLabel: UILabel! }
This allows you to tap into your StoryBrain Model. Good luck!
Upvotes: 1
Reputation: 3597
The issue is here:
StoryBrain.getStory()
^ Instance member 'getStory' cannot be used on type 'StoryBrain'
As the error indicates, getStory
is an instance method, meaning that you can only call it on instances of StoryBrain
. Here are a couple other suggestions:
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(...) {
...
}
}
If you initialize this object, like let brain = StoryBrain()
, then you can use instance members like advanceStory
and currentStoryTitle
on brain
. You’ll want to create this object/store it in whatever class you have updateUI
in. If you use the same brain from a couple different places, then you might want to use the singleton pattern, which you can see in the original edit to this answer.
Upvotes: 0