简体   繁体   English

泛型返回要求类型的结构

[英]Generics to return a struct of asked Type

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. 我成功的案例是Foo类型。

I have a Foo struct: 我有一个Foo结构:

struct Foo: Codable {
    let content: String
}

Now when I try to call the function xCode tells me: 现在,当我尝试调用xCode函数时,它告诉我:

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? 有人可以解释我在做什么吗?

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. 这样,您可以使用类的通用参数T代替函数中的T You also don't need the outputType parameter. 您也不需要outputType参数。

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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM