【问题标题】:Casting to a specified generic function parameter强制转换为指定的泛型函数参数
【发布时间】:2016-09-09 10:33:38
【问题描述】:

假设我有一个执行命令的Commander 对象。返回类型并不总是相同的,会根据命令而变化。

我希望能够使用将命令转发给指挥官的函数,测试结果是否属于某种类型(作为参数传递),然后在转换成功时调用成功闭包,以及否则失败关闭。

我尝试过像这样使用泛型参数:

func postCommand<T>(command: String, expectedResponseType: T, success: T -> Void, failure: (NSError?) -> Void) {
    Commander.execute(command, completion: { (response: AnyObject?) in
        guard let content = response as? T else {
            failure(nil)
            return
        }
        success(content)
    })
}

这样称呼它

self.postCommand("command", expectedResponseType: [String: AnyObject], success: { (content: [String: AnyObject]) in
    print("Success")
}) { (error: NSError?) in
    print("Failure")
}

但是我从编译器得到一个错误:

Cannot convert value of type '([String : AnyObject]) -> Void' to expected argument type '_ -> Void'

如果我尝试这样做:

guard let content = response as? expectedResponseType

编译器抱怨expectedResponseType 不是一个类型。

我不知道该怎么做。有没有可能?

【问题讨论】:

    标签: swift generics casting


    【解决方案1】:

    问题不在于转换,而在于expectedResponseType: 参数的类型。

    如果您希望将类型传递给函数,则需要使用the metatype type 作为参数类型。在这种情况下,你的函数的expectedResponseType: 参数应该是T.Type 类型——允许你传入一个类型来定义T

    func postCommand<T>(_ command: String, expectedResponseType: T.Type, success: (T) -> Void, failure: (NSError?) -> Void) {
        // ...
    }
    

    您还需要使用后缀.self 来引用您传递给expectedResponseType: 参数的任何内容的实际类型:

    self.postCommand("command", expectedResponseType: [String: AnyObject].self, success: { content in
        print("Success")
    }) { error in
        print("Failure")
    }
    

    虽然你应该注意T的类型可以直接从你传递给函数的成功闭包中推断出来:

    func postCommand<T>(_ command: String, success: (T) -> Void, failure: (NSError?) -> Void) {
        // ...
    }
    

    self.postCommand("command", success: { (content: [String: AnyObject]) in
        print("Success")
    }) { error in
        print("Failure")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2012-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多