数组 – 2D数组扩展Swift 3.1.1

数组 – 2D数组扩展Swift 3.1.1,第1张

概述我试图在 Swift 3.1.1中创建一个Array扩展,它支持将对象添加到2D Array中的某个索引,即使该数组尚未填充.扩展还应该提供在某个indexPath上获取对象的能力.我在Swift 2中有这个代码,但我似乎无法将它迁移到Swift 3.这是Swift 2代码: extension Array where Element: _ArrayProtocol, Element.Iterat 我试图在 Swift 3.1.1中创建一个Array扩展,它支持将对象添加到2D Array中的某个索引,即使该数组尚未填充.扩展还应该提供在某个indexPath上获取对象的能力.我在Swift 2中有这个代码,但我似乎无法将它迁移到Swift 3.这是Swift 2代码:

extension Array where Element: _ArrayProtocol,Element.Iterator.Element: Any {    mutating func addobject(_ anObject : Element.Iterator.Element,toSubarrayAtIndex IDx : Int) {        while self.count <= IDx {            let newSubarray = Element()            self.append(newSubarray)         }        var subarray = self[IDx]        subarray.append(anObject)    }    func objectAtIndexPath(_ indexPath: IndexPath) -> Any {        let subarray = self[indexPath.section]        return subarray[indexPath.row] as Element.Iterator.Element    }}

代码取自此answer.

解决方法 正如Martin在Swift 3.1中所说的 in his answer here,_ArrayProtocol is no longer public,因此意味着你不能将它用作扩展中的约束.

在您的情况下,一个简单的替代方法是将Array的Element约束为RangeReplaceableCollection – 它们都定义了一个init()需求,意味着“空集合”,以及一个append(_ :)方法,以便将元素添加到集合中.

extension Array where Element : RangeReplaceableCollection {    typealias InnerCollection = Element    typealias InnerElement = InnerCollection.Iterator.Element    mutating func fillingAppend(        _ newElement: InnerElement,toSubCollectionAtIndex index: Index) {        if index >= count {            append(contentsOf: repeatElement(InnerCollection(),count: index + 1 - count))        }        self[index].append(newElement)    }}

另请注意,我们将append作为单个调用进行(使用append(contentsOf :),确保我们只需要调整外部数组的大小一次.

对于从给定IndexPath获取元素的方法,您可以将内部元素类型约束为具有Int索引的Collection

// Could also make this an extension on Collection where the outer Index is also an Int.extension Array where Element : Collection,Element.Index == Int {    subscript(indexPath indexPath: IndexPath) -> Element.Iterator.Element {        return self[indexPath.section][indexPath.row]    }}

请注意,我已经使它成为下标而不是方法,因为我觉得它更符合Array的API.

你现在可以简单地使用这些扩展:

var arr = [[Int]]()arr.fillingAppend(6,toSubCollectionAtIndex: 3)print(arr) // [[],[],[6]]let indexPath = IndexPath(row: 0,section: 3)print(arr[indexPath: indexPath]) // 6

虽然当然如果您事先知道外部数组的大小,fillAppend(_:toSubCollectionAtIndex :)方法是多余的,因为您可以通过以下方式创建嵌套数组:

var arr = [[Int]](repeating: [],count: 5)

这将创建一个包含5个空[Int]元素的[[Int]]数组.

总结

以上是内存溢出为你收集整理的数组 – 2D数组扩展Swift 3.1.1全部内容,希望文章能够帮你解决数组 – 2D数组扩展Swift 3.1.1所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1007716.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存