Home > Software design >  Is there a simpler way to create an array of a certain length using another array as a repeat patter
Is there a simpler way to create an array of a certain length using another array as a repeat patter

Time:07-19

I want to create an app background made of coloured rectangles.

Each rectangle’s colour will be defined by an array of colours of a predefined length. This array is created by repeating an array serving as a ‘pattern’ until the length defined is reached.

Here is the code I have so far:

import SwiftUI

struct ContentView: View {
    private var colorArray: [Color] = [
        .blue,
        .green,
        .red
    ]
    @State private var newColorArray: [Color] = []
    private var arrayLength: Int = 4
    
    var body: some View {
        HStack {
            ForEach((0..<$newColorArray.count), id: \.self) { colorI in
                Rectangle()
                    .foregroundColor(newColorArray[colorI])
            }
        }
        .onAppear() {
            newColorArray = newArray(colorArray: colorArray, arrayLength: arrayLength)
        }
    }
    private func newArray(colorArray: [Color], arrayLength: Int) -> [Color] {
        var array: [Color] = []
        
        var colorI = 0
        for _ in 0..<arrayLength {
            if !colorArray.indices.contains(colorI) {
                colorI = 0
            }
            
            array.append(colorArray[colorI])
            
            colorI = colorI   1
        }
        return array
    }
}

What could I change to make it either faster or use less code?

CodePudding user response:

You asked for less code ;-)

import SwiftUI

struct ContentView: View {
    var body: some View {
        HStack{
           Color.blue
           Color.green
           Color.red
        }
    }
}

CodePudding user response:

There is no need to create the new array. Just use % to compute the index into colorArray.

This code replaces all of your code:

import SwiftUI

struct ContentView: View {
    private var colorArray: [Color] = [
        .blue,
        .green,
        .red
    ]

    private var arrayLength: Int = 4
    
    var body: some View {
        HStack {
            ForEach((0..<arrayLength), id: \.self) { colorI in
                Rectangle()
                    .foregroundColor(colorArray[colorI % colorArray.count])
            }
        }
    }
}
  • Related