收到错误消息:字符串不能转换为'T' [英] Getting error: String is not convertible to 'T'

查看:91
本文介绍了收到错误消息:字符串不能转换为'T'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码可以编译并正常工作:

This code compiles and works fine:

class Numbers {
    func operateOn<T>(_ num1: T, _ num2: T, do task: (T, T) -> ()) {
        task(num1, num2)
    }
}

let n = Numbers()
n.operateOn(1,2) {
    print(($0 + $1) * 10)
}

n.operateOn("l","ll") {
    print(($0 + $1))
}

以下代码的尚未编译.

Yet for for following code does not compile.

func process<T> (add: String, completion: (T) -> () ) {
    completion("k") // ERROR
}

但是我收到以下错误:

字符串"不能转换为"T"

'String' is not convertible to 'T'

我尝试传递Int,但又遇到另一个错误:

I tried passing an Int, but I just got another error:

'Int'不能转换为'T'

'Int' is not convertible to 'T'

IntString不能满足没有任何约束的一般要求吗?!

Can't an Int or a String satisfy a generic requirement that doesn't have any constraints?!

推荐答案

IntString是否不能满足通用要求 没有任何限制吗?!

Can't an Int or a String satisfy a generic requirement that doesn't have any constraints?!

可以.但这不是编译器给您错误的原因.

Sure it can. But that's not the reason the compiler is giving you an error.

考虑一下,如果将通用功能/参数约束在功能主体本身之内,会发生什么?它将不再是通用函数!

Think about it, what happens if you constrain a generic function/parameter within the function body itself?! It will no longer be a generic function!

想象一下您是否这样编写了operateOn函数:

Imagine if you had wrote your operateOn function as such:

class Numbers {
    func operateOn<T>(_ num1: T, _ num2: T, do task: (T, T) -> ()) {
        task("k", num2)
    }
}

您会说T是通用的吗?还是String类型?如果将其设置为String,那么num2可以是它想要的任何通用类型吗?不能!

Would you say that T is generic? Or that it's of type String? If you made it a String then can num2 be any generic type it wants to be? It can't!

如果类型为String,则不再是泛型.由于编译器不允许,它将引发该错误.

If it's of type String then it's no longer generic. Since the compiler can't allow that it will throw that error.

这篇关于收到错误消息:字符串不能转换为'T'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆