STATIC and CLASS
Posted by Wang Wei (@ONEVCAT) on 2015/01/28
The concept of "type scope scope" in Swift has two different keywords, each of which is a static and class . These two keywords do express this meaning, but in some other languages, including objective-c, we do not classify variable/class methods and static/static functions in special areas. But in Swift, these two keywords are not mixed.
In the context of a non- class type, we use it uniformly static to describe the scope of a type. This includes enum struct when describing type methods and type properties in and. In these two value types, we can declare and use stored properties within the scope of the type to evaluate properties and methods. staticThese are the scenarios that apply:
structPoint {Let x:DoubleLet y:DoubleStore PropertiesStaticLet zero =Point (x:0, Y:0)Calculated propertiesStaticvar ones: [point] {return [point (x: 1, y: 1), Point (x:-1, y: 1), point (x: 1, y:-1), point (x:-1, Y:-1)]} //type method static func Add (P1: point, P2: Point), point {return Point (x:p1.x + p2.x, Y:p1.y + p2.y)}}
enumThe situation is very similar to this, it is no longer listed.
classKeywords are much more understood than in the context of the class type, and can be used to modify the class method and the computed properties of the class. It is important to note that there class is no storage attribute present, if we write code like this:
class MyClass { class var bar: Bar?}
The compile time will get an error:
Class variables not yet supported
This is mainly because there is no concept of class variables in objective-c, for the sake of uniform and compatible running, it is not convenient to add this feature for the time being. Apple says it will consider storing variables of class type in an upgraded version in the future, and now we can only class class declare methods and evaluate properties in the keyword.
One of the more special is protocol . In Swift class , struct and enum both can be implemented in some protocol . So what keyword should we use if we want to protocol define a method or a computed property on a Type field? The answer is to use static a definition, but when implemented in a specific type or by the rule above: struct still used in or, the keyword is used in enum static class class -although it protocol is defined in static :
ProtocolMyProtocol {StaticFunc foo ()String}structMyStruct:MyProtocol {Staticfunc foo () string {return "mystruct"}}enum myenum: myprotocol {static func foo (), string {return " MyEnum "}} Class myclass: myprotocol {class Span class= "Hljs-func" >func foo (), string {return " MyClass "}}
Note
It was used as a keyword before Swift 1.2 protocol class , but this is really illogical. The Swift 1.2 has improved on this, and now it's just a matter of remembering class that everything else is used, except it's really specific static .
STATIC and CLASS