import SwiftUI
struct G<K> {
// static let n = 100 // error: static stored properties not supported in generic types
static var n: Int { 100 } // 👍 but computed is okay
}
print("\(G<Int>.n)") // print 100
// Can even implement some protocol with static get property on this generic type using static computed property
// I prefer to do this on some View instead of defining separate implementation of PreferenceKey
// does this have any negative like maybe generating extra code?
extension G: PreferenceKey {
static var defaultValue: Int { -1 }
static func reduce(value: inout Value, nextValue: () -> Value) {
value = nextValue()
}
}
print("Done!")
should the compile be helpful and suggest replacing static stored property with computed property?
Before knowing this, I resort to using global variable, now I simply make them all computed.
Good to know and keep in mind. I usually only need some constant Int or String, so it's no problem, as static stored or computed property of constant generate the same code. I wish the compile can analyze the code at hand and suggest replace with computed property if appropriate.
I mean that we use that as part of the suggestion, so that the compiler synthesize:
private let _shared: Int = 123
struct X<Value> {
var shared: Int { _shared }
}
but as I said, it's quite heavy for a suggestion.
It could work for standard-library types, but I don't see how it could apply to a more general one. Even something simple like Array is already a struct containing class-based storage. If not for its value semantic, Array should actually be treated like a class.