简体   繁体   English

为结构创建一个变量(快速)

[英]Create A Variable for Struct (Swift)

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 ViewController1

override func viewDidLoad() {
        super.viewDidLoad()

structToBeReferenced = songs
}

ViewController2 ViewController2

override func viewDidLoad() {
            super.viewDidLoad()

    structToBeReferenced = songs2
    }

ViewController3 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 . 基本上,我只想创建一个可以更改的变量,以便在ViewController1 structToBeReferenced设置为songs ViewController2 sets structToBeReferenced to songs2 . ViewController2structToBeReferenced设置为songs2 So that in ViewController3 whenever theFunction() is called, the right library is referenced. 因此,在ViewController3中,每当theFunction() ,都会引用正确的库。

I hope that made sense. 我希望这是有道理的。 I just need to know what the variable, structToBeReferenced , needs to equal. 我只需要知道structToBeReferenced变量需要等于什么。 Thanks for the help! 谢谢您的帮助!

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: 现在,在视图控制器中,您可以使用协议类型声明struct属性:

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 . 这样,两种结构类型都可以保证具有title属性,但是只要它们符合SongProtocol ,就可以使用任何一种。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM