Wednesday, April 3, 2024
HomeiOS Developmentios - The best way to correctly shuffle a 2-dimensional array in...

ios – The best way to correctly shuffle a 2-dimensional array in Swift?


I’ve a 2D array of UIImages that I create from slicing a sq. formed picture into 9 equal components. This works high-quality.

@State personal var orderedImages: [[UIImage]]?
@State personal var shuffledImages: [[UIImage]]?

I shuffle the orderedImages and retailer them into the shuffledImages array like so:

shuffledImages = orderedImages?.shuffled()

After which show them in a 3×3 grid like so:

GeometryReader { geometry in
    VStack(spacing: 2) {
        ForEach(0..<3, id: .self) { row in
            HStack(spacing: 2) {
                ForEach(0..<3, id: .self) { column in
                    Picture(uiImage: shuffledImages[row][column])
                        .resizable()
                        .scaledToFill()
                        .body(width: (geometry.dimension.width - (2*2)) / 3, top: (geometry.dimension.width - (2*2)) / 3)
                        .clipped()
                }
            }
        }
    }
}

Nonetheless, evidently shuffling solely rearranges the rows of the orderedImages array. Which means that if you happen to see the 3×3 grid, every picture within the row is in sequence with its neighbour (the reference picture is on the prime adopted by the shuffled picture displayed under):

enter image description here
enter image description here

How do I shuffle the orderedImages array in order to randomise the place of each UIImage object?



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments