直到Swift 2.2,我才能做到这一点:
for each in [myUIButton,myUILabel] {
each.hidden = true
}
但是在Swift 3中这是不可接受的,因为标签,按钮等不是同一种元素。我已经将第2行更改为 each.isHidden = true
它抛出“异构集合文字...... ”错误。当您通过添加[Any]来修复它时,它会将“ Cast'Any'抛出到'AnyObject .. ”错误。
是否可以轻松解决此问题?
答案 0 :(得分:1)
数组中的所有项都必须有一个公共子类,例如myButton和myLabel(大概)中的UIView
,以便进行类型推断。
let label = UILabel()
let button = UIButton()
let collectionView = UICollectionView()
let tableView = UITableView()
let array = [label, button, collectionView, tableView] // Type: [UIView]
for item in array {
item.isHidden = true
}
此代码适用于您的目的。
此外,如果它们都符合相同的协议,则必须明确命名它们符合的协议。
protocol Commonality {
func commonMethod() { ... }
}
class ThingA: Commonality { ... } // Correctly conform to Commonality
class ThingB: Commonality { ... } // Correctly conform to Commonality
class ThingC: Commonality { ... } // Correctly conform to Commonality
let array: [Commonality] = [ThingA(), ThingB(), ThingC()]
for item in array {
item.commonMethod()
}
这应该也可以,但您必须明确命名通用协议。否则(至少在我的测试中),它会将所有内容向下转换为Any
。
答案 1 :(得分:1)
找到一个具有isHidden
属性的公共祖先类,并明确地转换为它:
for each in [myUIButton, myUILabel] as [UIView] {
each.isHidden = true
}
答案 2 :(得分:0)
告诉Swift它是[Any]
数组:
for each in [myButton,myLabel,x,y,z] as [Any] {
each.hideen = true
}
但是,您会收到错误原因Any
没有名为hideen
的属性(错字?)。