[英]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: 我有一个switch语句,在每种情况下,我都有许多语句如下:
star1.isHidden = true
star1 in this instance is an image view. 在这种情况下,star1是图像视图。 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.
有没有一种方法可以将其分配给多个变量,例如star2,star3等。在10种情况下,它相当于许多行代码,我不禁想到有一种更有效/更易理解的方法。
If you are using interface builder, you could use OutletCollection. 如果使用接口构建器,则可以使用OutletCollection。 Otherwise, you could create an array of all the variables and use a for-in loop.
否则,您可以创建所有变量的数组并使用for-in循环。
You can extend a sequence of UIView
s that will iterate through the views and set each hidden. 您可以扩展
UIView
的序列,该序列将遍历视图并设置每个视图。
extension Sequence where Element == UIView {
func setHidden(_ hide: Bool) {
forEach { $0.isHidden = hide }
}
}
let viewsToHide = [star1, star2, star3]
viewsToHide.setHidden(true)
There are many ways, one of the most common would be a for
loop. 有很多方法,最常见的一种是
for
循环。 In this instance you would need a collection of stars such as an array: [Star]()
在这种情况下,您将需要一组星星,例如一个数组:
[Star]()
for (star in stars) {
star.isHidden = true
}
There isn't enough information about your setup to give you a much better recommendation. 没有足够的信息来提供有关您的设置的更好的建议。
If the objects are NSObject-based, you can use key-value coding. 如果对象是基于NSObject的,则可以使用键值编码。 This is in a Swift playground, but it works everywhere:
这是在Swift操场上,但可以在任何地方使用:
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.