[英]Check if the generic type is a function type in Swift
I have defined a generic class as follows我已经定义了一个通用类如下
class A<T:Any>{
var value:T?
}
I would like to know how I could limit T to be of a function type and can write code like value() in Class A.我想知道如何将 T 限制为函数类型,并且可以在 A 类中编写类似 value() 的代码。
let a = A<()->()>()
Referring to Apple's Documentation :参考苹果的文档:
Generic code enables you to write flexible, reusable functions and types that can work with any type , subject to requirements that you define.
通用代码使您能够根据您定义的要求编写灵活、可重用的函数和类型,这些函数和类型可以与任何类型一起使用。
This is the main purpose of using Generics.这是使用泛型的主要目的。
In your case, probably, this is the not right way of how to use them.就您而言,这可能是使用它们的不正确方式。 You might want to make more simple:
您可能想要更简单:
typealias funcion = ()->()
class A {
private var value:funcion?
init(value: @escaping funcion) {
self.value = value
}
func doSomething() {
print("do something 01")
if let iplementedValue = value {
iplementedValue()
}
print("do something 02")
}
}
Instantiation:实例化:
let aObject = A(value: {
print("I want to this in the middle of my \"doSomething\"")
})
aObject.doSomething()
The output should looks like:输出应如下所示:
do somthing 01
I want to this in the middle of my "doSomething"
do somthing 02
Hope that helped.希望有所帮助。
I was having a similar problem, I ended up solving it like so:我遇到了类似的问题,我最终解决了这样的问题:
First I defined a generic type representing a function which accepts a single parameter, and return value:首先,我定义了一个泛型类型,表示一个接受单个参数和返回值的函数:
typealias Monad<A, R> = (A) -> (R)
I then defined my class to take a generic type parameter for the input type.然后我定义了我的类来为输入类型采用一个泛型类型参数。 In my case, every function passed was going to return void so I didn't need two type parameters.
就我而言,传递的每个函数都将返回 void,因此我不需要两个类型参数。
class HoldsMyCallback<A> {
let callback: Monad<A, Void>
init(callback: @escaping Monad<A, Void>) {
self.callback = callback
}
}
...
let funcKoozie = HoldsMyCallback<Int> {
print("keep my \($0) function cold")
}
funcKoozie.callback(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.