Reputation: 573
I have a switch statement and in each of the cases I have a number of statements which read:
star1.isHidden = true
star1 in this instance is an image view. Is there a way of assigning this to multiple variables, such as star2, star3 etc. With 10 cases it amounts to many lines of code and I can't help but think there's a more efficient/readable way of doing it.
Upvotes: 1
Views: 931
Reputation: 7400
You can extend a sequence of UIView
s that will iterate through the views and set each hidden.
extension Sequence where Element == UIView {
func setHidden(_ hide: Bool) {
forEach { $0.isHidden = hide }
}
}
let viewsToHide = [star1, star2, star3]
viewsToHide.setHidden(true)
Upvotes: 2
Reputation: 6705
If the objects are NSObject-based, you can use key-value coding. This is in a Swift playground, but it works everywhere:
class Star:NSObject {
public var hidden = false
}
let star1 = Star()
let star2 = Star()
let star3 = Star()
let star4 = Star()
let star5 = Star()
let starMap:NSArray = [star1, star2, star3, star4]
starMap.setValue(true, forKey: "hidden")
Upvotes: 0
Reputation: 7265
There are many ways, one of the most common would be a for
loop. In this instance you would need a collection of stars such as an array: [Star]()
for (star in stars) {
star.isHidden = true
}
There isn't enough information about your setup to give you a much better recommendation.
Upvotes: 0
Reputation: 16104
If you are using interface builder, you could use OutletCollection. Otherwise, you could create an array of all the variables and use a for-in loop.
Upvotes: 3