Protocol negotiation not recognized in a shared function

I would appreciate any understanding of this question that I have. I am trying to create a generic function in Swift that accepts any type that conforms to a specific protocol. However, when I pass the appropriate type to this method, I get a compiler error saying the class does not match.

Here's my protocol:

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

      

And here is the class I made that conforms to this protocol:

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

      

Finally, here is my general function that lives in another class:

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

      

Now when I call the method like this:

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

      

I am getting 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 don't understand why this will happen when the class Foo

declares and implements the SettableTitle

match.

All this in a simple playground in Xcode 8.3 (latest non-beta). Can anyone see something I am doing wrong here?

+3


source to share


1 answer


Your function expects 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 General

0


source







All Articles