Swift 2D Array Extension Error

2019-07-09 04:31发布

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
}

}

2条回答
Root(大扎)
2楼-- · 2019-07-09 05:26

@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
    }
}
查看更多
爷的心禁止访问
3楼-- · 2019-07-09 05:30

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

查看更多
登录 后发表回答