将通用免费函数转换为数组扩展 [英] Convert generic free function into Array extension

查看:118
本文介绍了将通用免费函数转换为数组扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一些代码来执行游程编码和解码。我有我的编码函数作为Array的扩展方法,但我无法以类似的方式进行解码。这可能吗?

  func runLengthDecode< T:Equatable>(_ runLengthEncoding: [(element:T,count:Int)]) - > [T] {
return runLengthEncoding.flatMap {repeatElement($ 0.element,count:$ 0.count)}
}

我希望这个函数也是Array上的一个方法。一些行为:

 扩展数组< T>其中Element ==(元素:T,count:Int){
func runLengthDecode() - > [T] {
return self.flatMap {repeatElement($ 0.element,count:$ 0.count)}
}
}

解决方案

不是限制数组扩展,而是将约束移动到您的方法中:

 扩展数组{
func runLengthDecode< T:Equatable>() - > [T]其中Element ==(element:T,count:Int){
return flatMap {repeatElement($ 0.element,count:$ 0.count)}
}
}

或简单地

 扩展数组{
func runLengthDecode< T:Equatable>() - > [T]其中Element ==(element:T,count:Int){
return flatMap(repeatElement)
}
}


I wrote some code to perform run length encoding and decoding. I have my encoding function as a method in an extension to Array, but I can't make the decoding in a similar fashion. Is this possible? I can't find any ways of introducing new generic types into extensions.

func runLengthDecode<T: Equatable>(_ runLengthEncoding: [(element: T, count: Int)]) -> [T] {
    return runLengthEncoding.flatMap{ repeatElement($0.element, count: $0.count)}
}

I wish this function were a method on Array, as well. Something along the lines of:

extension Array<T> where Element == (element: T, count: Int) {
    func runLengthDecode() -> [T] {
        return self.flatMap{ repeatElement($0.element, count: $0.count)}
    }
}

解决方案

Instead of constraining the array extension move the constraint to your method:

extension Array {
    func runLengthDecode<T: Equatable>() -> [T] where Element == (element: T, count: Int)  {
        return flatMap{ repeatElement($0.element, count: $0.count) }
    }
}

or simply

extension Array {
    func runLengthDecode<T: Equatable>() -> [T] where Element == (element: T, count: Int)  {
        return flatMap(repeatElement)
    }
}

这篇关于将通用免费函数转换为数组扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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