无法推断通用参数 'T'/无法显式特化通用函数

Generic parameter 'T' could not be inferred / Cannot explicitly specialize a generic function

我在 Xcode 7.3.1 的 Swift 项目中编写了一个带有此签名的函数:

func DLog<T>(@autoclosure object: () -> T, _ file: String = #file, _ function: String = #function, _ line: Int = #line) {
}

编译器针对此调用抱怨 Generic parameter 'T' could not be inferred

DLog({ var text = "Returning output list\n"; for outline in outlines { text = text + outline.debugDescription + "\n"; }; return text; })

当我尝试提供它抱怨的类型时 Cannot explicitly specialize a generic function:

DLog<String>({ var text = "Returning output list\n"; for outline in outlines { text = text + outline.debugDescription + "\n"; }; return text; })

我尝试了更多的方法,但没有一个能让编译器满意。我也未能找到解决此案例的提示。

如何在 () => T 参数中构建文本并将其正确传递给函数?

我不知道为什么会这样,但是在swift3中编译它会出现这个错误信息:

Unable to infer complex closure return type; add explicit type to disambiguate

所以我尝试为闭包显式添加 return 类型:

DLog(
    { () -> String in 
        var text = "Returning output list\n" 
        for outline in outlines { 
            text = text + outline.debugDescription + "\n"; 
        } 
        return text 
    }
)

成功了。

由于 @autoclosure 属性,编译失败。当您将某些表达式传递给采用 @autoclosure 的函数时,编译器会创建一个没有参数的闭包,该闭包 returns 是该表达式的结果。因此,当您传递 { var text = "Returning output list\n"; for outline in outlines { text = text + outline.debugDescription + "\n"; }; return text; } 时,编译器会创建一个返回闭包的闭包返回字符串。

要解决此问题,您可以将 () 添加到表达式的末尾:

DLog({ () -> String in var text = "Returning output list\n"; for outline in outlines { text = text + outline.debugDescription + "\n"; }; return text; }())

或将表达式简化为简单的方法调用,例如

DLog(outlines.reduce("Returning output list\n") { [=11=] + .debugDescription + "\n"; })