Reputation: 42642
I have a School
struct:
public struct School {
...
}
Then, I have an extension for it, in which I declare a static enum:
extension School {
// Compiler error: Declaration cannot be marked 'static'
static enum Level: String {
case Middle = "middle"
}
}
But I got compiler error as mentioned in comment above, how can I declare a static enum in extension then?
Upvotes: 1
Views: 1302
Reputation: 3195
Only properties and methods of a type can be marked static. (Enum is a value type like struct) In addition if you have a class that has a static method or property and require it to be subclassed it should be marked class and not static.
Upvotes: 1
Reputation: 63369
In Java, inner types have access to the members of the enclosing type. The static
keyword is used to block such access and to indicate that the type is independent of the members of its enclosing type.
Swift doesn't do that from the start, so it doesn't have a use for static
inner types.
Upvotes: 0
Reputation: 54755
An enum
is a type and hence it cannot be marked static. Even if you declare an enum
inside a class, it will be accessible through the class type and not through an instance. In Swift, the static
keyword can be used to mark type properties, but since enum
is a type itself, it cannot be a property and hence cannot be marked static
.
struct School {
}
extension School {
enum Level: String {
case Middle = "middle"
}
}
You can access the enum
through the School
type, you don't need to create an instance.
School.Level.Middle
Upvotes: 8