0

I am trying to extract just the id's from the Properties Array to form a separate array. So far I have come up with this:

struct Interactions: View {

@State var A: [Properties] = [
    .init(id: 5, name: "Five"),
    .init(id: 8, name: "Eight"),
    .init(id: 2, name: "Two")
]
var body: some View {

    List(loadIdArray(), id: \.self) { i in
        Text("\(i)")
    }


}

func loadIdArray() -> [Int] {

    let ids: [Int] = [1, 2]
    for i in 0 ..< self.A.count {
        let ids = [self.A[i].id, self.A[i + 1].id]
        return ids
    }
    return ids
}
}

The problem is that I would have to manually type each [self.A[I + ...].id] which defeats the purpose of the function.

The answer I want is for loadIdArray() = [5, 8, 2] and for it to do this automatically depending on how many items are in the 'A' array.

2
  • You should start by separating your view and your model; This is very important in SwiftUI as it is declarative. Once you have a model to hold your array, you can use a computed variable to provide an Array with the ids Commented Apr 11, 2020 at 2:02
  • @Paulw11 would you by any chance be able to write that out as code? I think it's a problem with my iteration as it only presents one self.A.id and has to be manually typed out Commented Apr 11, 2020 at 2:14

1 Answer 1

3

how about using this:

func loadIdArray() -> [Int] {
    return self.A.map { $0.id }
}
Sign up to request clarification or add additional context in comments.

1 Comment

THANK YOU! I've been stuck on this for way too long

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.