I am wishing to implement a pattern similar to Notification.Name
where anyone can add one later via an extension
, like this:
public protocol Foo {
var bar: String { get }
}
public struct FooImpl: Foo {
public let bar: String
}
public extension Foo {
public static let baz: Foo = FooImpl(bar: "baz")
}
// Ideal usage:
someFuncThatTakesAFoo(.baz)
This seems fine to me, but I get a confusing error when compiling:
/path/to/main.swift:24:23: error: static stored properties not supported in generic types
public static let baz: Foo = FooImpl(bar: "baz")
~~~~~~ ^
What's going on here, and what's a solution?
That is a weird error message, but your code shouldn't compile anyways. Stored properties are not supported in extensions, hence the error.
By removing the static
keyword and just leaving baz
as a stored property, you get a meaningful error:
extensions may not contain stored properties
Changing the declaration to a computed property (and hence declaring it mutable) the error magically disappears.
public protocol Foo {
var bar: String { get }
}
public struct FooImpl: Foo {
public let bar: String
}
public extension Foo {
public static var baz: Foo {
return FooImpl(bar: "baz")
}
}