Jason
Jason

Reputation: 3535

Swift, why Struct's static property cannot be used in "computed property" but can be used in "stored property"

The code snippet shows 4 different ways to access a static property of a struct. Interesting enough that only the 4th one gets the error: "Static member 'size' cannot be used on instance of type 'Learn_W'" Could you help explain why the other three can access the static property of the struct without using Self. as prefix, but only the test4 has to add the Self.as prefix to access the static property size ?

struct Learn_W: View {
    
    private static let size: CGFloat = 50
    
    
    let test1 = size
    
    var test2 = size
    
    struct test3 {
        let a = size
        var b = size
    }

    var test4: CGFloat {
        get {return size}
    } // "Static member 'size' cannot be used on instance of type 'Learn_W'"

My speculation: the difference is whether the static property is accessed in “Computed property” or “Stored property”. I guess that it’s related to the initialization process of a struct. For stored property, it’s always initialized before an instance is available, so the initialization process would automatically refer the internal “self” as the struct type itself. But “computed property” is not initialized when the instance is available, and it’s evaluated only (not 100% sure, it’s just my speculation) when it’s called in the form instance.computed_property, therefore, it’s being accessed directly though an instance, and in that context the “self” automatically refers to the instance but not type

Upvotes: 0

Views: 226

Answers (1)

Alexander
Alexander

Reputation: 63281

In all 4 cases, you reference to size is shorthand for self.size.

For each call originating from a static context (the first 3), self is referring to the Learn_W type itself, which has a size, so it works.

In the last case, the call is happening from an instanced context, where self refers to an instance of Learn_W (not Learn_W). Since instances of Learn_W don’t have a size, the lookup is invalid.

Upvotes: 1

Related Questions