0

I have two structs and a class. when I call on the class in which I have created instances for one of the structs. I want to append them to an array in the other struct when the class is called. Is there a way to do this?

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])
}

This won't work, is there another way to do it?

1
  • Is it group1 or group? Commented Nov 25, 2018 at 9:49

2 Answers 2

1

You can't execute code like that in the class body, it needs to be in the scope of a function or a constructor.

To me it looks like you want to do something like

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])
    }
}

And then

let example = Example()
example.runExample()
Sign up to request clarification or add additional context in comments.

1 Comment

thank you, i'll rework how I got things arranged and try that!
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]
    }

}

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.