加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

数组 – 2D数组扩展Swift 3.1.1

发布时间:2020-12-14 04:43:09 所属栏目:百科 来源:网络整理
导读:我试图在 Swift 3.1.1中创建一个Array扩展,它支持将对象添加到2D Array中的某个索引,即使该数组尚未填充.扩展还应该提供在某个indexPath上获取对象的能力.我在Swift 2中有这个代码,但我似乎无法将它迁移到Swift 3.这是Swift 2代码: extension Array where E
我试图在 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]]数组.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读