相当于Swift中的一个JS对象数组。我当前的实现抛出错误 'property initializers run before self'。这可能吗?

Equivalent to a JS array of objects in Swift. My current implementation throws an error 'property initializers run before self'. Is this possible?

我希望我的用户循环浏览他们看到图片的界面,然后可以按下按钮来生成属于图片的声音。

为此,我尝试在 Swift 中构建一个包含两个键值对的数据结构,以便我可以在任何位置的当前索引处调用每个 属性 的值我的用户恰好是。

其中一个属性是具有 UIImage 值的 image,另一个是具有 string 值的 sound。在尝试了几件事之后,我能想到的最好的是下面的实现,但是它会在我的 animals 变量中的每个变量上抛出以下错误。错误:Cannot use instance member 'bird' within property initializer; property initializers run before 'self' is available.

当我在局部范围内声明 animals 变量时,即在函数内部,它工作正常。但我需要该变量具有全局范围。我搜索了很多,不得不承认我并不完全理解抛出的错误。

谁能指出我做错了什么?

XCode中的代码:

class element {
    let image : UIImage
    let sound : String
    init (image : UIImage, sound : String) {
            self.image = image
            self.sound = sound
        }
}

let monkey = element(image : UIImage(named: "Baviaan")!, sound : "monkey")
let donkey = element(image : UIImage(named: "Donkey")!, sound : "donkey")
let horse = element(image : UIImage(named: "Horse")!, sound : "horse")
let lion = element(image : UIImage(named: "Leeuw")!, sound : "lion")
let elephant = element(image : UIImage(named: "Olifant")!, sound : "elephant")
let sheep = element(image : UIImage(named: "Sheep")!, sound : "sheep")
let dog = element(image : UIImage(named: "Tekkel")!, sound : "dog")
let chicken = element(image : UIImage(named: "toktok")!, sound : "chicken")
let bird = element(image : UIImage(named: "birds")!, sound : "bird")

var animals = [bird,chicken,dog,donkey,elephant,horse,lion,monkey,sheep]

错误图片:

这种全局变量是不好的做法。不要那样做。更好的方法是静态 属性

struct Element {
    let image : UIImage
    let sound : String

    static let animals = [
        Element(image: UIImage(named: "Baviaan")!, sound: "monkey"),
        Element(image: UIImage(named: "Donkey")!, sound: "donkey"),
        Element(image: UIImage(named: "Horse")!, sound: "horse"),
        Element(image: UIImage(named: "Leeuw")!, sound: "lion"),
        Element(image: UIImage(named: "Olifant")!, sound: "elephant"),
        Element(image: UIImage(named: "Sheep")!, sound: "sheep"),
        Element(image: UIImage(named: "Tekkel")!, sound: "dog"),
        Element(image: UIImage(named: "toktok")!, sound: "chicken"),
        Element(image: UIImage(named: "birds")!, sound: "bird")
   ]
}

或更短

struct Element {
    let image : UIImage
    let sound : String
    
    static let animals = [
        ("Baviaan", "monkey"), ("Donkey", "donkey"),
        ("Horse", "horse"), ("Leeuw", "lion"),
        ("Olifant", "elephant"), ("Sheep", "sheep"),
        ("Tekkel", "dog"), ("toktok", "chicken"), ("birds", "bird")]
        .map{Element(image: UIImage(named: [=11=].0)!, sound: [=11=].1)}
}

你得到的动物有

Element.animals