【发布时间】:2016-07-02 13:16:59
【问题描述】:
我正在尝试创建一个可以采用可选参数的通用函数。 到目前为止,这是我所拥有的:
func somethingGeneric<T>(input: T?) {
if (input != nil) {
print(input!);
}
}
somethingGeneric("Hello, World!") // Hello, World!
somethingGeneric(nil) // Errors!
它适用于String,如图所示,但不适用于nil。
将它与nil 一起使用会出现以下两个错误:
error: cannot invoke 'somethingGeneric' with an argument list of type '(_?)'
note: expected an argument list of type '(T?)'
我做错了什么,我应该如何正确声明/使用这个函数?另外,我想让函数的使用尽可能简单(我不想做nil as String?之类的事情)。
【问题讨论】:
标签: swift function generics null function-declaration