Swift:如何将一个类中的结构实例添加到另一个结构中的数组

时间:2018-11-25 08:48:48

标签: arrays swift class struct

我有两个结构和一个类。当我调用为其中一个结构创建实例的类时。我想在调用该类时将它们附加到另一个结构的数组中。有办法吗?

struct People {
    let name: String
    let age: Int
}

struct Group {
    var groupOfPeople: [People] = []
}

class example {
    var group1 = Group()
    let person1 = People(name: "Jay", age: 44)
    let person2 = People(name: "Sarah", age: 35)
    let person3 = People(name: "Eric", age: 21)
    let person4 = People(name: "Tara", age: 10)
    group.groupOfPeople.append(contentsOf: [person1, person2, person3, person4])
}

这行不通,还有另一种方法吗?

2 个答案:

答案 0 :(得分:1)

您不能像在类主体中那样执行代码,它必须在函数或构造函数的范围内。

对我来说,您似乎想做

class Example {
    func runExample() {
        var group1 = Group()
        let person1 = People(name: "Jay", age: 44)
        let person2 = People(name: "Sarah", age: 35)
        let person3 = People(name: "Eric", age: 21)
        let person4 = People(name: "Tara", age: 10)
        group1.groupOfPeople.append(contentsOf: [person1, person2, person3, person4])
    }
}

然后

let example = Example()
example.runExample()

答案 1 :(得分:0)

class example{
    var group1 = Group()
    let person1 = People(name: "Jay", age: 44)
    let person2 = People(name: "Sarah", age: 35)
    let person3 = People(name: "Eric", age: 21)
    let person4 = People(name: "Tara", age: 10)

    init() {
        group1.groupOfPeople = [person1, person2, person3, person4]
    }

}