本文介绍了是否有可能在Swift中创建一个通用闭包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  func myfunc< T>(i:T) - > T {
return
}

是否可以使这个通用函数关闭?

  let myfunc = {< T>(i:T) - > T in 
return
}

这不起作用...

解决方案

不,因为变量和表达式不能通用。只有通用函数和通用类型。




澄清:在某些语言中,可以使用通用量词类型,像 forall a。 a - >一个。但在Swift中,类型不能有一个通用的量词。所以表达式和值不能是通用的。函数声明和类型声明可以是通用的,但是当你使用这样的通用函数或者这样的泛型类型的实例时,选择某种类型(可以是实型或类型变量)作为类型参数,然后你得到的价值不再是自己的通用。


func myfunc<T>(i:T) -> T {
    return i
}

is it possible to make this generic function a closure?

let myfunc = { <T>(i:T) -> T in
    return i
}

this doesn't work...

解决方案

No, because variables and expressions can't be generic. There are only generic functions and generic types.


To clarify: In some languages you can have types with a universal quantifier, like forall a. a -> a. But in Swift, types cannot have a universal quantifier. So expressions and values cannot be themselves generic. Function declarations and type declarations can be generic, but when you use such a generic function or an instance of such a generic type, some type (which could be a real type or a type variable) is chosen as the type argument, and thereafter the value you get is no longer itself generic.

这篇关于是否有可能在Swift中创建一个通用闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 23:16
查看更多