4

I would appreciate any insight on this issue I'm having. I'm trying to create a generic function in Swift that accepts any type that conforms to a specific protocol. However, when I pass a conforming type into this method, I get a compiler error saying the class doesn't conform.

Here's my protocol:

protocol SettableTitle {
    static func objectWithTitle(title: String)
}

And here's a class I've made that conforms to this protocol:

class Foo: SettableTitle {
    static func objectWithTitle(title: String) {
        // Implementation
    }
}

Finally, here's my generic function that lives in a different class:

class SomeClass {
    static func dynamicMethod<T: SettableTitle>(type: T, title: String) {
        T.objectWithTitle(title: title)
    }
}

Now, when I invoke the method like this:

SomeClass.dynamicMethod(type: Foo.self, title: "Title string!")

I get the following compiler error: error: argument type 'Foo.Type' does not conform to expected type 'SettableTitle' SomeClass.dynamicMethod(type: Foo.self, title: "Title string!")

I can't understand why this would happen when the class Foo declares and implements SettableTitle conformance.

All this is in a simple playground in Xcode 8.3 (latest non-beta). Can anyone see anything I'm doing wrong here?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Drew
  • 113
  • 9

1 Answers1

0

Your function is expecting an object that implements SettableTitle, not a type.

Instead, you need to do T.Type, and it will work:

class SomeClass {
  static func dynamicMethod<T: SettableTitle>(type: T.Type, title: String) {
    T.objectWithTitle(title: title)
  }
}

Source: Using a Type Variable in a Generic

sschale
  • 5,168
  • 3
  • 29
  • 36