0

I want to pass the type of my struct ("myStruct") to my function ("testFunc") which is bound by a protocol ("TestProtocol")

protocol TestProtocol {
    func getName() -> String
}

func testFunc <T: TestProtocol> (with type: T) {
    print ("testFunc")
}

struct myStruct: TestProtocol {
    var name: String
    func getName() -> String {
        return name
    }
}

testFunc(with: myStruct.self)

But I get the error that myStruct.Type does not conform to TestProtocol; yet it clearly does!

WishIHadThreeGuns
  • 1,225
  • 3
  • 17
  • 37
  • 1
    `myStruct.Type` (the metatype object of `myStruct`) does not conform to the protocol. *Instances* of `myStruct` conform to the protocol. Related: https://stackoverflow.com/q/33112559/3141234 – Alexander Aug 01 '19 at 02:44
  • 1
    Also, structs (all types, actually) should be `UpperCamelCase` in Swift, and [don't write setters in Swift.](https://github.com/amomchilov/Blog/blob/master/Stop%20writing%20getters%20and%20setters%20in%20Swift.md) – Alexander Aug 01 '19 at 02:46
  • One is a typo, the idea of writing getters or setters based on random GitHub link? Thanks, but stay on topic for the question. – WishIHadThreeGuns Aug 01 '19 at 06:19
  • 1
    It's a common enough of issue in the thousands of questions I've seen that I found it worthwhile to spend my time and write it up nicely, rather than rewriting the same comments. I suggest you take a look, hopefully you'll find it quite insightful – Alexander Aug 01 '19 at 12:03

2 Answers2

0

Your testFunc is expecting an instance of a class that conforms to TestProtocol. So just create one:

testFunc(with: myStruct(name: "John"))

To pass a type of your myStruct:

func testFunc <T: TestProtocol> (with type: T.Type) {
    print ("testFunc")
}

testFunc(with: myStruct.self)

Pavel Kozlov
  • 993
  • 6
  • 16
0

Use T.Type as the parameter type.

protocol TestProtocol {
    func getName() -> String
}

func testFunc <T: TestProtocol> (with type: T.Type) {
    print ("testFunc")
}

struct MyStruct: TestProtocol {
    var name: String
    func getName() -> String {
        return name
    }
}

testFunc(with: MyStruct.self)
Ricky Mo
  • 6,285
  • 1
  • 14
  • 30