0

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!

3
  • 2
    Not really sure what are you trying to achieve. What's the purpose of declaring two completely unrelated, though identical in implementation, structs? Commented Jul 17, 2017 at 12:24
  • @mag_zbc I have 2 song libraries. Both display on a UITableView. When a user clicks on the cell, it opens a player view. Both tableviews open the same player view. I need this so that the right song library will be referenced in the player view. Commented Jul 17, 2017 at 12:39
  • @JacobCavin, well, then you need two collections, not two different, but similar types. Commented Jul 17, 2017 at 12:42

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.