Reputation: 2329
I have two structs which look like this:
struct Song {
var title: String
var artist: String
}
var songs: [Song] = [
Song(title: "Title 1", artist: "Artist 1"),
Song(title: "Title 2", artist: "Artist 2"),
}
and
struct Song2 {
var title: String
var artist: String
}
var songs2: [Song] = [
Song(title: "Title 1", artist: "Artist 1"),
Song(title: "Title 2", artist: "Artist 2"),
}
I want to create a variable that changes so on diffrent events either the first struct will be referenced, or the second struct will be referenced. Like this.
var structToBeReferenced = //What goes here?
ViewController1
override func viewDidLoad() {
super.viewDidLoad()
structToBeReferenced = songs
}
ViewController2
override func viewDidLoad() {
super.viewDidLoad()
structToBeReferenced = songs2
}
ViewController3
func theFunction() {
label.text = structToBeReferenced[thisSong].title
}
Basically, I just want to create a variable that can be changed so that in ViewController1, it sets structToBeReferenced
to songs
. ViewController2 sets structToBeReferenced
to songs2
. So that in ViewController3 whenever theFunction()
is called, the right library is referenced.
I hope that made sense. I just need to know what the variable, structToBeReferenced
, needs to equal. Thanks for the help!
Upvotes: 0
Views: 2932
Reputation: 1170
Create a protocol that both structs conform to. Something like this:
protocol SongProtocol {
var title: String { get set }
}
Then your structs would conform to the protocol like this:
struct Song: SongProtocol {
var title: String
var artist: String
}
Now in your view controllers you can declare the struct property using the protocol type:
var structToBeReferenced: SongProtocol = // your struct here
This way, both struct types are guaranteed to have the title property but you can use which ever one you need to so long as they conform to the SongProtocol
.
Upvotes: 2