调用函数时显式指定泛型约束 [英] Explicitly specify generic type constraint when calling function

查看:528
本文介绍了调用函数时显式指定泛型约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在 Swift 中显式指定泛型函数的泛型类型。假设我有以下函数定义,它基本上创建了一个泛型类型的空数组 T

I am wondering wether or not is possible in Swift to explicitly specify the generic type of a generic function. Assuming I have the following function definition which basically creates an empty array of a generic type T:

func bar<T>() -> [T] {
    return [T]()
}

var foo = bar()

结果

results in


无法推断泛型参数'T' / b>

generic parameter 'T' could not be inferred

这是完全有道理的,因为在这里确实没有任何信息可以推断任何东西。

which makes total sense since there really is no information to infer anything here.

但不幸的是,我尝试通过以下方式明确指定类型约束失败:

But unfortunately my attempt at specifying the type constraint explicitly via the following failed as well:

var foo = bar<Int>()




错误:无法显式地专用通用函数

error: cannot explicitly specialize a generic function




  • 为什么我无法做到这一点?

  • 这是一种语言规范,不能显式指定泛型类型吗?
  • 有什么方法可以指定函数的泛型类型?

  • 推荐答案


    有什么方法可以指定泛型类型的函数?

    What way is there to specify the generic type of the function?

    通用类型可以从上下文中推断出来:

    The generic type can be inferred from the context:

    func bar<T>() -> [T] {
        return [T]()
    }
    
    let val1 = bar() as [Int] // or:
    let val2 : [Int] = bar()
    

    (我无法回答其他问题。)

    (I cannot answer the other questions.)

    这篇关于调用函数时显式指定泛型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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