2

I am very new to Swift, so excuse me if this is a dumb question.

I have a JSON X array of objects, which I load into my app and pass around views (I have a defined struct for it). Now in another view I have a new struct, which looks like this:

struct Pin: Identifiable {
    var name: String
    let id = UUID()
}

and later make an array like so:

@State private var pins: [Pin] = []

How can I make this array to contain Pin objects, but made from my existing X array. What I mean that each new Pin inside pins array would have the values of Pin(name: X.name[0] and so on for each element in my X array.

So my final pins array should look something like:

[Pin(name: x.name[0]...), Pin(name: x.name[1]...), Pin(name: x.name[2]...)...]
2
  • 1
    What exactly is X array? And what about the image in the new array? Commented Dec 21, 2020 at 23:39
  • @pawello2222 the X array is an array of objects, each with a name, description and couple other fields I don't need for this particular view. You can ignore the image, I was gonna have it but ultimately decided not to, will remove it from the code sample :) Commented Dec 21, 2020 at 23:41

1 Answer 1

4

You can use map to convert one array to another:

pins = x.map { Pin(name: $0.name) }

or, slower but shows another way of using map:

pins = x.map(\.name).map(Pin.init)
Sign up to request clarification or add additional context in comments.

1 Comment

AH amazing, that did exactly what I needed it to do! I am a JavaScript dev and use maps every single day, but for some reason it did not occur to me that they can also be used in Swift... Anyway, thank you so much!

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.