【发布时间】:2015-10-13 12:22:49
【问题描述】:
好吧,所以 Swift 在某些领域很出色,但在某些领域并不那么出色。
我正在尝试根据另一个数组中的数组在一个数组中查找一个元素。
我的应用中有一些视觉元素有时需要隐藏和显示,而不是编写手动逻辑来显示和隐藏视觉元素, 相反,我将它们全部放在一个数组中并调用一个函数,该函数需要一个包含我要隐藏的元素的引用数组。
例如:我有 10 个按钮(或不同对象的混合,例如UIImageViews和UILabels等),我们可以将它们称为 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
}
}
}
}
【问题讨论】:
-
既然你确切地知道数组包含
UIButton实例,你为什么将elements声明为AnyObject? -
@vadian 在问题中他指出他想要混合类型,而不仅仅是
UIButton。 -
@Charles A.:
UILabel,UIImageView和UIButton都是UIView的子类,所以UIViewlike in your answer比AnyObject好很多 -
@vadian 同意(显然,鉴于我的回答)。我以为你是在建议他使用
UIButton类型的集合。