Reputation: 24892
I noticed that some functions in Swift
protocols
have the static
keyword. However, when you implement the function, you must remove the static
keyword to make the compiler happy.
public static func <(lhs: Self, rhs: Self) -> Bool
What does static
mean in the context and what is its purpose?
Upvotes: 1
Views: 1764
Reputation: 116
Static properties and methods
Swift lets you create properties and methods that belong to a type, rather than to instances of a type. This is helpful for organizing your data meaningfully by storing shared data.
Swift calls these shared properties "static properties", and you create one just by using the static keyword. Once that's done, you access the property by using the full name of the type. Here's a simple example:
struct TaylorFan {
static var favoriteSong = "Shake it Off"
var name: String
var age: Int
}
let fan = TaylorFan(name: "James", age: 25)
print(TaylorFan.favoriteSong)
So, a Taylor Swift fan has a name and age that belongs to them, but they all have the same favorite song.
Because static methods belong to the class rather than to instances of a class, you can't use it to access any non-static properties from the class.
Upvotes: 2
Reputation: 285039
From the Xcode 8 beta 4 release notes:
Operators can be defined within types or extensions thereof. For example:
struct Foo: Equatable { let value: Int static func ==(lhs: Foo, rhs: Foo) -> Bool { return lhs.value == rhs.value } }
Such operators must be declared as
static
(or, within a class,class final
), and have the same signature as their global counterparts. As part of this change, operator requirements declared in protocols must also be explicitly declaredstatic
:protocol Equatable { static func ==(lhs: Self, rhs: Self) -> Bool }
Upvotes: 4