swiftswiftuiswift5swift-structs

What is the maximum number of state variables I can have in a Swift UI Struct and will the performance slow down with increase in variables?


What is the maximum number of state variables I can have in a Swift UI Struct ?

struct Example: View {

    @State var first : Bool = true
    @State var second: Double = 94.4
    @State var third: CGFloat = 45.45
        .
        .
        .
     How many maximum ?

    var body: some View {
        Text("Hello ")
    }

}

Also, does having a lot of state variables actually slow down the app ? I need some clarity on the scalability of this thing cuz I am new to declarative programming :P


Solution

  • Just to get you started with an answer,

    1. It's hard to believe there is any performance issue. "Declarative programming" doesn't actually exist. It's just a compiler / runtime / whatever doing some checking. There's no really substantative, paradigm difference from other structures in the pipeline.

    If, incredibly, you were doing real performance programming, perhaps scientific or for a game or the like, you'd never in a million years be involved in anything like this, so it's of no relevance.

    Also, it's worth nothing that anything at all related to UI on your phone, uses a staggering amount of processing power. Rendering any one text character! which happens to be on screen at that time, is an amazing dance of spline curve dithering, blitting, etc. Issue such as "checking done by the runtime system" are really irrelevant except in incredibly unusual cases.

    Summary: don't consider performance in this milieu.

    1. How many can you have? If you paste in a few thousand, it works fine. It's hard to believe there's any limit.

    Summary: It's possible you're thinking of a limit like "30". There is no such limit whatsoever.

    (There could be some technical, arcane limit - like 64 million - but it's totally irrelevant to what you're doing!)


    Management summary: relax and enjoy, these are non-issues.


    More info on the particular case

    I am trying to animate, i am using withAnimation to display percentage progress in a ring

    For the number of state variables described (say, anything less than 100,000 - you are using about "20"), the extra overhead for the checking is utterly irrelevant. It is so low you could not measure it.

    TBC this is likely not the most elegant way to do this but, regarding the specific performance question asked, it is absolutely a non-issue. Enjoy!