在Swift 2.1中查找数组中的对象

vai*_*aid 1 arrays object ios swift

好吧,斯威夫特在可能的领域是伟大的,而在某些方面并不是那么好.

我试图在一个数组中找到一个元素,基于另一个数组中的数组.

我的应用程序中有一些我需要隐藏和显示的视觉元素,而不是编写手动逻辑来显示和隐藏可视元素,而是将它们全部放在一个数组中并调用一个函数需要一个包含引用的数组我要隐藏的元素.

例如:我有10个按钮(或不同的对象,如混合UIImageViewsUILabels等等),我们可以调用它们B1虽然B10.

如果我在某些时候需要隐藏除B3,B4,B7,B9和B10之外的所有元素,我只需调用hideAllExcept(ignore: Array<AnyObject>)(} 并且func处理剩下的部分.

哪些隐藏和显示的元素有时可以完全随机,因此这种方法可以非常强大.

但是,当尝试检查第一个数组中的元素是否包含在第二个数组中时,我收到以下错误: Cannot invoke 'contains' with an argument list of type '(anObject: AnyObject)

如何在Swift 2.1中实现这种效果?

我目前的尝试看起来像这样(显然不起作用):

class myCollectionOfThings : UIView {
    let B1  = UIButton(type: UIButtonType.Custom)
    let B2  = UIButton(type: UIButtonType.Custom)
    let B3  = UIButton(type: UIButtonType.Custom)
    let B4  = UIButton(type: UIButtonType.Custom)
    let B5  = UIButton(type: UIButtonType.Custom)
    let B6  = UIButton(type: UIButtonType.Custom)
    let B7  = UIButton(type: UIButtonType.Custom)
    let B8  = UIButton(type: UIButtonType.Custom)
    let B9  = UIButton(type: UIButtonType.Custom)
    let B10 = UIButton(type: UIButtonType.Custom)

    var elements = Array<AnyObject>()

    func prep(parent: UIView){
        elements = [B1, B2, B3, B4, B5, B6, B7, B8, B9, B10]

        //I will be setting up all my UIButtons by code here...
    }

    func hideAllExcept(ignoreElements: Array<AnyObject>){
        var hide = Bool()

        for i in  0...ignoreElements.count - 1{
            if elements.contains(ignoreElements[i]){ //I get the error here
                //Hide the element here
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Cha*_* A. 8

我不相信Swift数组的contains方法就是这样.您正在调用的contains方法接受一个将为数组中的每个元素调用的块,Bool如果元素匹配,则由您返回.

你考虑过用过Set吗?考虑到可用的属性和功能,这似乎是一种更简单的方法Set.请注意,您必须声明它是采用Hashable协议的类型,但是UIView如果您想要隐藏元素(hidden声明为on UIView),您似乎无论如何都希望使用它作为您的类型.

class myCollectionOfThings : UIView {
    let B1  = UIButton(type: UIButtonType.Custom)
    let B2  = UIButton(type: UIButtonType.Custom)
    let B3  = UIButton(type: UIButtonType.Custom)
    let B4  = UIButton(type: UIButtonType.Custom)
    let B5  = UIButton(type: UIButtonType.Custom)
    let B6  = UIButton(type: UIButtonType.Custom)
    let B7  = UIButton(type: UIButtonType.Custom)
    let B8  = UIButton(type: UIButtonType.Custom)
    let B9  = UIButton(type: UIButtonType.Custom)
    let B10 = UIButton(type: UIButtonType.Custom)

    var elements = Set<UIView>()

    func prep(parent: UIView){
        elements = [B1, B2, B3, B4, B5, B6, B7, B8, B9, B10]

        //I will be setting up all my UIButtons by code here...
    }

    func hideAllExcept(ignoreElements: Set<UIView>){
        for element in elements.subtract(ignoreElements) {
            element.hidden = true
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可能还希望将元素设置ignoreElements为不被隐藏,除非您在其他地方执行此操作.你可以轻松地做到这一点:

for element in ignoreElements {
    element.hidden = false
}
Run Code Online (Sandbox Code Playgroud)