Swift 2D阵列扩展 [英] Swift 2D Array Extension

查看:72
本文介绍了Swift 2D阵列扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对Array类型进行扩展,以便能够使用2D数组.实际上,我是在Objective-C中完成的,下面的代码像个魅力一样工作.但是我真的迷上了Swift.

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:

错误:无法使用类型为([[AnyObject])'的参数列表调用'append'

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

我将不胜感激.

推荐答案

@brimstone的答案很接近,但是如果我正确理解了您的问题,它就是一个 [AnyObject] 的数组,这意味着它应该看起来像这样:

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

这篇关于Swift 2D阵列扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆