【发布时间】:2017-05-26 11:49:04
【问题描述】:
我正在尝试在 Swift 3.1.1 中创建一个 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。
【问题讨论】:
-
首先在 Swift3 中没有
_ArrayProtocol了。我想我不再需要where子句了?不确定.. -
相关:swift.org/migration-guide(也许你已经知道了,如果不知道,那会有很大帮助)
-
我真的不确定如何将代码迁移到 Swift 3。我尝试不使用
where子句而不是Element.Iterator.Element我只是使用Element但是当我尝试执行let newSubArray = Element()我得到Element cannot be constructed because it has no accessible initiliaziers我还尝试扩展Collection而不是Array并使用Iterator.Element而不是Element但再次没有成功。 -
我只是无法以某种方式获得语法和一切正确..
标签: arrays swift multidimensional-array swift3