Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带泛型函数参数的Swift数组扩展_Swift_Generics - Fatal编程技术网

带泛型函数参数的Swift数组扩展

带泛型函数参数的Swift数组扩展,swift,generics,Swift,Generics,我正在使用Swift 4,并寻找一种方法,为具有类型参数的数组集合创建扩展函数 typealias Listener<T> = (T) -> Void typealias侦听器=(T)->Void 但是,无法创建下面的扩展(使用未声明的类型“T”) 扩展序列,其中元素==侦听器{ func callAll(t:t){ self.forEach{$0(t)} } } 有什么方法可以让它工作吗?您不能在代码中像T这样的扩展的标题处引入新的泛型参数,但每个方法都可以有泛型参数

我正在使用Swift 4,并寻找一种方法,为具有类型参数的数组集合创建扩展函数

typealias Listener<T> = (T) -> Void
typealias侦听器=(T)->Void
但是,无法创建下面的扩展(使用未声明的类型“T”)

扩展序列,其中元素==侦听器{
func callAll(t:t){
self.forEach{$0(t)}
}
}

有什么方法可以让它工作吗?

您不能在代码中像
T
这样的扩展的标题处引入新的泛型参数,但每个方法都可以有泛型参数

typealias Listener<T> = (T) -> Void

extension Sequence {
    func callAll<T>(t: T)
        where Element == Listener<T>
    {
        self.forEach { $0(t) }
    }
}
let listeners: [Listener<Int>] = [
    { print($0) },
    { print($0 * 2) },
]

listeners.callAll(t: 2)
typealias侦听器=(T)->Void
扩展序列{
func callAll(t:t)
其中元素==侦听器
{
self.forEach{$0(t)}
}
}
让侦听器:[侦听器]=[
{打印($0)},
{打印($0*2)},
]
listeners.callAll(t:2)

您不能在代码中像
T
这样的扩展的标题处引入新的泛型参数,但每个方法都可以有泛型参数

typealias Listener<T> = (T) -> Void

extension Sequence {
    func callAll<T>(t: T)
        where Element == Listener<T>
    {
        self.forEach { $0(t) }
    }
}
let listeners: [Listener<Int>] = [
    { print($0) },
    { print($0 * 2) },
]

listeners.callAll(t: 2)
typealias侦听器=(T)->Void
扩展序列{
func callAll(t:t)
其中元素==侦听器
{
self.forEach{$0(t)}
}
}
让侦听器:[侦听器]=[
{打印($0)},
{打印($0*2)},
]
listeners.callAll(t:2)

可以给你一些提示。可以给你一些提示。简单的解决方案所以我把它标记为答案,谢谢简单的解决方案所以我把它标记为答案,谢谢