Home > Net >  Using a Class Type as function input parameter without initializing it
Using a Class Type as function input parameter without initializing it

Time:11-16

I have a class which conforms to a certain protocol.

    protocol MyProtocol {
    func doSomething()
}


class MyClass: MyProtocol {
    func doSomething() { }

}

In another class I have a function which has input parameter of MyProtocol.

func customFunction(with: MyProtocol) { }

When I call this function with input parameter MyClass (which actually conforms to MyProtocol), I get an error saying MyClass does not conform to MyProtocol

customFunction(with: MyClass)

I know I should actually use an instance of MyClass, but I just need the type of MyClass. Is there a workaround to do this?

CodePudding user response:

You need to define the function to take the type rather than an instance of the type as an argument

func customFunction(with type: MyProtocol.Type) {}

Then you can call it with a type conforming to the protocol

customFunction(with: MyClass.self)
  • Related