2

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 this error no matter what I do:

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

I'd appreciate any help.

pkamb
  • 33,281
  • 23
  • 160
  • 191
Vitalii Vashchenko
  • 1,777
  • 1
  • 13
  • 23

2 Answers2

5

@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:

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
    }
}
Aaron Rasmussen
  • 13,082
  • 3
  • 42
  • 43
0

You need to say what the array element type is in the extension. Try this:

extension _ArrayType where Generator.Element == AnyObject {
    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
    }
}

From this question: Extend array types using where clause in Swift

pkamb
  • 33,281
  • 23
  • 160
  • 191
brimstone
  • 3,370
  • 3
  • 28
  • 49