Home > Back-end >  How can I call a variable from an array that has a type of struct?
How can I call a variable from an array that has a type of struct?

Time:09-07

How can I call the image variable that is inside the array?

static let data: [Meditation] = [
        Meditation(title: "1 Minute Relaxing Meditation", description: "Clear your mind and slumber into nothingness. Allocate only a few moments for a quick breather.", duration: 70, track: "meditation1", image: "Ambient"),
        Meditation(title: "1 Minute Relaxing Meditation", description: "Clear your mind and slumber into nothingness. Allocate only a few moments for a quick breather.", duration: 70, track: "meditation1", image: "World"),
        Meditation(title: "1 Minute Relaxing Meditation", description: "Clear your mind and slumber into nothingness. Allocate only a few moments for a quick breather.", duration: 70, track: "meditation1", image: "Pop"),
        Meditation(title: "1 Minute Relaxing Meditation", description: "Clear your mind and slumber into nothingness. Allocate only a few moments for a quick breather.", duration: 70, track: "meditation1", image: "HipHop"),
        Meditation(title: "1 Minute Relaxing Meditation", description: "Clear your mind and slumber into nothingness. Allocate only a few moments for a quick breather.", duration: 70, track: "meditation1", image: "R&B"),
        Meditation(title: "1 Minute Relaxing Meditation", description: "Clear your mind and slumber into nothingness. Allocate only a few moments for a quick breather.", duration: 70, track: "meditation1", image: "EDM")
    ]

I have tried; however, it does not work.

meditation.data.image

CodePudding user response:

Since data is an array, you can’t just call .image. You have to know which element’s image you want then access it.

If you want the first element, simply call:

meditation.data.first?.image

If not, you need to filter the array or use an index in order to get the element you want:

meditation.data[3].image//fourth image

CodePudding user response:

As data variable is an array of Meditation types.

For accessing the value in an array we need to use the index value as given below:

For the 0th index, we can access image as meditation.data[0].image // Ambient

For the 1st index, we can access image as meditation.data[1].image // World

For the 2nd index, we can access image as meditation.data[2].image // Pop

For the 3rd index, we can access image as meditation.data[3].image // HipHop

For the 4th index, we can access image as meditation.data[4].image // R&B

For the 5th index, we can access image as meditation.data[5].image // EDM

  • Related