Reputation: 4632
Up until Swift 2.2 I was able to do this:
for each in [myUIButton,myUILabel] {
each.hidden = true
}
but in Swift 3 this is not acceptable because label, button etc are not the same kind of element. I have already changed line 2 to each.isHidden = true
It throws "Heterogeneous collection literal..." error. When you fix it by adding [Any], it throws "Cast 'Any' to 'AnyObject.." error.
Is there an easy fix to this problem?
Upvotes: 0
Views: 149
Reputation: 47886
Find a common ancestor class having isHidden
property, and explicitly cast to it:
for each in [myUIButton, myUILabel] as [UIView] {
each.isHidden = true
}
Upvotes: 1
Reputation: 459
All items in your array must have a common subclass, like UIView
in the case of myButton and myLabel (presumably) in order for type inference to take place.
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
}
This code will work for your purposes.
Furthermore, if they all conform to the same protocol, you must explicitly name the protocol they conform to.
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()
}
This should work as well, but you must explicitly name the common protocol. Otherwise (at least in my tests), it downcasts everything down to Any
.
Upvotes: 1
Reputation: 2132
Tell Swift it's an [Any]
array:
for each in [myButton,myLabel,x,y,z] as [Any] {
each.hideen = true
}
But then you will get an error cause Any
doesn't have a property called hideen
(typo?).
Upvotes: 0