MM1010
MM1010

Reputation: 573

How do you assign a property to multiple variables in Swift?

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

Answers (4)

AdamPro13
AdamPro13

Reputation: 7400

You can extend a sequence of UIViews 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

David S.
David S.

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")

Playground Result

Upvotes: 0

ColdLogic
ColdLogic

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

mginn
mginn

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

Related Questions