Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

language design - Why no stored type properties for classes in swift?

Working through The Swift Programming Language, I was surprised to see that, unlike structures and enumerations, classes do not support stored type properties.

This is a common feature of other OO languages so I assume there was a good reason they decided not to allow it. But I'm not able to guess what that reason is, especially since structures (and enumerations) have them.

Is it simply that it's early times for Swift and it just hasn't been implemented yet? Or is there a deeper reason behind language design decision?

BTW, "stored type property" is Swift terminology. In other languages these might be called class variables. Example code:

struct FooStruct {
    static var storedTypeProp = "struct stored property is OK"
}

FooStruct.storedTypeProp // evaluates to "struct stored property is OK"

class FooClass {
    class var computedClassProp: String { return "computed class property is OK" }

    // class var storedClassProp = "class property not OK" // this won't compile
}

FooClass.computedClassProp // evaluates to "computed class property is OK"

Edit:

I now realize this limitation is trivial to work around, e.g., by using a nested structure with stored properties:

class Foo {
    struct Stored {
        static var prop1 = "a stored prop"
    }
}

Foo.Stored.prop1 // evaluates to "a stored prop"
Foo.Stored.prop1 = "new value"
Foo.Stored.prop1 // evaluates to "new value"

That seems to preclude their being some deep inscrutable language design reason for this limitation.

Given that and the wording of the compiler message that Martin Gordon mentions, I have to conclude that this is simply something (minor) left out.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The compiler error is "Class variables not yet supported" so it seems like they just haven't implemented it yet.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...