Home > Enterprise >  Outsource function to a separate struct in SwiftUI
Outsource function to a separate struct in SwiftUI

Time:10-21

Since I just started programming with Swift I have the following (maybe very stupid) question: I would like to outsource the function tick into a separate struct but don't know exactly how to do that. Is this even possible?

struct Ticks{
    
}

struct ContentView: View {

func tick(at tick: Int) -> some View {
    HStack {
        Rectangle()
            .fill(Color.primary)
            .opacity(tick % 20 == 0 ? 1 : 0.4)
            .frame(width: tick % 4 == 0 ? 15 : 7, height: 2)
        
        Spacer()
    }.rotationEffect(Angle.degrees(Double(tick)/240 * 360))
}
    
    var body: some View {
       
        ZStack {
            ForEach(0..<60*4) { tick in
                self.tick(at: tick)
            }
            .padding(.horizontal, 10.0)
        }
    }
}

CodePudding user response:

Since the function doesn't use any instance properties you can make it static and move it as is to the Ticks struct

struct Ticks{
    static func tick(at tick: Int) -> some View {
        HStack {
            Rectangle()
                .fill(Color.primary)
                .opacity(tick % 20 == 0 ? 1 : 0.4)
                .frame(width: tick % 4 == 0 ? 15 : 7, height: 2)

            Spacer()
        }.rotationEffect(Angle.degrees(Double(tick)/240 * 360))
    }
}

and then access it from the other view

ForEach(0..<60*4) { tick in
    Ticks.tick(at: tick)
}

CodePudding user response:

The idiomatic way is to turn Ticks into another View, and reuse it from the original view. SwiftUI promotes small, reusable views, that are composed to build bigger hierarchies:

struct Ticks: View {
    let tick: Int

    var body: some View {
        HStack {
            Rectangle()
                .fill(Color.primary)
                .opacity(tick % 20 == 0 ? 1 : 0.4)
                .frame(width: tick % 4 == 0 ? 15 : 7, height: 2)
        
            Spacer()
        }.rotationEffect(Angle.degrees(Double(tick)/240 * 360))
    }
}

struct ContentView: View {
    var body: some View {      
        ZStack {
            ForEach(0..<60*4) { tick in
                Tick(tick: tick)
            }
            .padding(.horizontal, 10.0)
        }
    }
}

  • Related