gpt4 book ai didi

ios - Swift 二维数组扩展

转载 作者:可可西里 更新时间:2023-11-01 00:36:47 24 4
gpt4 key购买 nike

我正在尝试对 Array 类型进行扩展,以便能够使用 2D 数组。事实上,我是在 Objective-C 中完成的,下面的代码非常有效。但我真的坚持使用 Swift。

extension Array {
mutating func addObject(anObject : AnyObject, toSubarrayAtIndex idx : Int) {
while self.count <= idx {
let newSubArray = [AnyObject]()
self.append(newSubArray)
}

var subArray = self[idx] as! [AnyObject]
subArray.append(anObject)
}

func objectAtIndexPath(indexPath : NSIndexPath) -> AnyObject {
let subArray = self[indexPath.section] as! Array
return subArray[indexPath.row] as! AnyObject
}
}

无论我做什么我都会得到这个错误:

Error: Cannot invoke 'append' with an argument list of type '([AnyObject])'

如果有任何帮助,我将不胜感激。

最佳答案

@brimstone 的答案很接近,但如果我正确理解你的问题,它是一个 [AnyObject] 数组,这意味着它应该如下所示:

extension Array where Element: _ArrayType, Element.Generator.Element: AnyObject {
mutating func addObject(anObject : Element.Generator.Element, toSubarrayAtIndex idx : Int) {
while self.count <= idx {
let newSubArray = Element()
self.append(newSubArray) // ERROR: Cannot invoke 'append' with an argument list of type '([AnyObject])'
}

var subArray = self[idx]
subArray.append(anObject)
}

func objectAtIndexPath(indexPath: NSIndexPath) -> AnyObject {
let subArray = self[indexPath.indexAtPosition(0)]
return subArray[indexPath.indexAtPosition(1)] as Element.Generator.Element
}
}

关于ios - Swift 二维数组扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36212848/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com