0
votes

I'm having a function like this:

func someFunction<T: Codable>(x: Double, y: Double, outputClass: T, completionBlock: CompletionBlock)

the completionblock is:

enum Result {
    case success(Codable)
    case failure(String?)
}

typealias CompletionBlock = (Result) -> Void

What I want to achieve is that when you call the function for example like this:

someFunction(x: 12, y: 12, outputClass: Foo.self) { (result) in
   switch result {
   case .success(let result):
}

That my let result in the success case is of type Foo.

I have a Foo struct:

struct Foo: Codable {
    let content: String
}

Now when I try to call the function xCode tells me:

Argument type 'Foo.Type' does not conform to expected type 'Encodable'

But the struct conforms to the type Codable and that is encodable & decodable.

Can someone explain me what I'm doing wrong?

1
You are passing an instance of Type, not an instance of an object that conforms to Codable. - Paulw11

1 Answers

0
votes

I think you need to wrap your function inside a generic class, and put the enum inside the class as well. This way, you can use the generic parameter T of the class instead of the T in the function. You also don't need the outputType parameter.

class SomeClass<T: Codeable> {
    class func someFunction(x: Double, y: Double, completionBlock: CompletionBlock) {

    }

    enum Result {
        case success(T)
        case failure(String?)
    }

    typealias CompletionBlock = (Result) -> Void
}

struct Foo: Codeable {

}

// usage
SomeClass<Foo>.someFunction(x: 0, y: 0) { (x) in
    switch x {
    case .success(let result):
        // result is now of type Foo
    case .failure:
        break
    }
}