加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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.
将它与nil一起使用会产生以下两个错误:

error: cannot invoke 'somethingGeneric' with an argument list of type '(_?)'
note: expected an argument list of type '(T?)'

我做错了什么,我应该如何正确地声明/使用这个功能?另外,我想让函数的使用尽可能简单(我不想做像nil这样的字符串?).

解决方法

我想编译器无法弄清楚T只是来自nil.

以下工作正常,但例如:

somethingGeneric(可选<字符串> .None)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读