我有两个看起来像这样的结构:
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"),
}
和
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"),
}
我想创建一个在不同事件上发生变化的变量,或者引用第一个结构,或者引用第二个结构。像这样。
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
}
基本上,我只想创建一个可以更改的变量,以便在 ViewController1 中将structToBeReferenced
设置为songs
。 ViewController2 将structToBeReferenced
设置为songs2
。因此,在 ViewController3 中,只要调用theFunction()
,就会引用正确的库。
我希望这是有道理的。我只需要知道变量structToBeReferenced
需要等于什么。谢谢你的帮助!
答案 0 :(得分:2)
创建两个结构符合的protocol。像这样:
protocol SongProtocol {
var title: String { get set }
}
然后你的结构符合这样的协议:
struct Song: SongProtocol {
var title: String
var artist: String
}
现在,在视图控制器中,您可以使用协议类型声明struct属性:
var structToBeReferenced: SongProtocol = // your struct here
这样,两种结构类型都保证具有title属性,但只要符合SongProtocol
,就可以使用所需的结构类型。