In Swift, the concept of type scope scope has two different keywords, namely static and class. These two keywords do express this meaning, but in other languages, including objective-c, we do not specifically classify variable/class methods and static variables/static functions. But in Swift, these two keywords are not mixed.
In the type context of non class, we uniformly use static to describe the scope of the type. This includes the presentation of type methods and type attributes in enum and struct. In these two value types, we can declare and use storage properties within the scope of a type, and compute properties and methods. Static applies to scenarios that have these:
struct Point {let
x:double let
y:double
//Storage property
static Let zero = Point (x:0, y:0)//
Compute Property
STA tic var 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)
}
}
The case of an enum is very similar to this one and is no longer enumerated.
The class keyword is much more understood than it is in the class type context, and can be used to modify the class method and the computed properties of the class. To pay special attention to the memory attributes that are not present in class, if we write code like this:
Class MyClass {
class var bar:bar?
}
An error is obtained at compile time:
Class variables not yet supported
This is mainly because the concept of class variables is not available in objective-c, and for the sake of runtime unification and compatibility, it is temporarily inconvenient to add this feature. Apple said that in the future, it would consider a class-type storage variable in an upgraded version, and now we can only declare methods and computed properties in class with the class keyword.
One of the more special is protocol. class, struct, and enums can be protocol in Swift. So if we want to define a method on a Type field or compute a property in protocol, which keyword should we use? The answer is to use class to define, but when implemented, follow the rules above: Use the class keyword in class, and still use static--in struct or enum although the class is used in protocol definition:
Protocol MyProtocol {
class func foo ()-> String
}
struct Mystruct:myprotocol {
static func foo () ; string {return
' MyStruct
}}
'
enum Myenum:myprotocol {
static func foo ()-> string {
return ' MyEnum '
}
}
class Myclass:myprotocol {
class func foo ()-> String {return
"MyClass"
}
}