Happy discovery: static stored properties are not allowed in generic type, but computed are!

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.

1 Like

Stored and computed properties are different though.

class X {}
struct Y {
  // Same X every time
  static let a = X()

  // New X every time
  static var b: X { X() }
}

and whether this difference matter depends solely on the type of X. I'm not sure if it'd be wise to suggest computed property from stored one.

We could add private global var to act as a storage, but IMO, it's getting huge for a compiler's suggestion.

1 Like

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.

We could add private global var

fileprivate let xxx = 123

is this not good enough?

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.

1 Like
Terms of Service

Privacy Policy

Cookie Policy