Swift – 将Nil作为带有可选参数的泛型函数的参数
发布时间:2020-12-14 04:48:06 所属栏目:百科 来源:网络整理
导读:我正在尝试创建一个可以采用可选参数的泛型函数. 这是我到目前为止所拥有的: func somethingGenericT(input: T?) { if (input != nil) { print(input!); }}somethingGeneric("Hello,World!") // Hello,World!somethingGeneric(nil) // Errors! 它如图所示使
我正在尝试创建一个可以采用可选参数的泛型函数.
这是我到目前为止所拥有的: func somethingGeneric<T>(input: T?) { if (input != nil) { print(input!); } } somethingGeneric("Hello,World!") // Hello,World! somethingGeneric(nil) // Errors! 它如图所示使用String,但不能使用nil. error: cannot invoke 'somethingGeneric' with an argument list of type '(_?)' note: expected an argument list of type '(T?)' 我做错了什么,我应该如何正确地声明/使用这个功能?另外,我想让函数的使用尽可能简单(我不想做像nil这样的字符串?). 解决方法
我想编译器无法弄清楚T只是来自nil.
以下工作正常,但例如: somethingGeneric(可选<字符串> .None) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |