Search code examples
swiftgenericscompiler-errorsswift-extensions

Error claims a protocol is a generic type, but no generics are used


I am wishing to implement a pattern similar to Notification.Name where anyone can add one later via an extension, like this:

Swift 4

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?


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")
        }
    }