I'm trying to make an Extension to the Array type so to be able to work with 2D arrays. In fact, I did this in Objective-C and the code below worked like a charm. But I really stuck in 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
}
}
I get the error I mentioned in code sample no matter what I do. I'd appreciate any help. Thanks.
UPDATE thanks to Roman Sausarnes
The correct code is this:
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])'
}
self[idx].append(anObject)
}
func objectAtIndexPath(indexPath: NSIndexPath) -> AnyObject {
let subArray = self[indexPath.indexAtPosition(0)]
return subArray[indexPath.indexAtPosition(1)] as Element.Generator.Element
}
}
@brimstone's answer is close, but if I understand your question correctly, it is an array of
[AnyObject]
, which means it should look like this:You need to say what the array element type is in the extension. Try this:
From this question