简体   繁体   English

Swift 2D 数组扩展

[英]Swift 2D Array Extension

I'm trying to make an Extension to the Array type so to be able to work with 2D arrays.我正在尝试对 Array 类型进行扩展,以便能够使用 2D 数组。 In fact, I did this in Objective-C and the code below worked like a charm.事实上,我在 Objective-C 中做到了这一点,下面的代码就像一个魅力。 But I really stuck in Swift.但我真的坚持使用 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])'错误:无法使用类型为“([AnyObject])”的参数列表调用“append”

I'd appreciate any help.我很感激任何帮助。

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

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来自这个问题: Extend array types using where clause in Swift

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM