如何实现扁平化作为无型铸造阵列的延伸? [英] How to implement flatten as an extension on an Array without type casting?

查看:142
本文介绍了如何实现扁平化作为无型铸造阵列的延伸?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 扩展阵列{
  FUNC扁平化< T>() - GT; T [] {
    让XS =(self作为任意)作为数组<数组< T>>
    返回xs.reduce(T []()+)
  }
}

它的工作原理,但我不知道是否需要所有这些类型转换。

有没有更好的办法?

为了便于比较,这里是在执行迅速扩展库之一。我不知道,如果他们拥有了一切想通了,太 - 实施始于以下评论:


  

//有仍然有一些工作,在这里做



解决方案

您不能在斯威夫特延长特定类型的泛型类型的:

 扩展阵列<&诠释GT; {
}


  

    

错误:非标称型数组不能延长


  

但你可以写一个函数,特定类型的数组。如果你想扁平化阵列(阵列&LT的数组; T []> T [] [] 或阵列>)你的函数的签名是这样的:

  FUNC扁平化< T> (数组:数组< T []>) -  GT; T []

这需要 T 的数组的数组,并返回 T 的数组。然后,您可以用你的方法减少

  FUNC扁平化< T> (数组:数组< T []>) -  GT; T [] {
    返回array.reduce(T []()+)
}

extension Array {
  func flatten<T>() -> T[] {
    let xs = (self as Any) as Array<Array<T>>
    return xs.reduce(T[](), +)
  }
}

It works, but I'm not sure if all those casts are required.

Is there a better way?

For comparison, here is the implementation in one of the swift extension libraries. I'm not sure if they have it all figured out too -- their implementation begins with the following comment:

// There's still some work to do here

解决方案

You can't extend a specific type of a generic type in Swift:

extension Array<Int> {
}

error: non-nominal type 'Array' cannot be extended

But you can write a function that takes a specific type of array. If you want to flatten an array of arrays (Array<T[]>, T[][] or Array>) your functions signature would look like this:

func flatten<T> (array: Array<T[]>) -> T[]

It takes an array of arrays of T and returns an array of T. You can then use your approach with reduce:

func flatten<T> (array: Array<T[]>) -> T[] {
    return array.reduce(T[](), +)
}

这篇关于如何实现扁平化作为无型铸造阵列的延伸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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