Reputation: 231
is there a way to create an array of UIViews?
I've tried bot I can't add an values
var views = [UIView?](count: 64, repeatedValue: nil)
This results in nil
views[0]?.backgroundColor = UIColor.redColor()
I also tried
var views = NSMutableArray()
for (var a = 0; a<100; a++){
views[a] = UIView()
}
views[0].backgroundColor = UIColor.redColor() // fails
Upvotes: 5
Views: 10481
Reputation: 92489
With Swift 4, you can use one of the following ways in order to solve your problem.
Range
and map(_:)
let range = 0 ... 5
let array = range.map { _ in UIView() }
Range
and for loopvar array = [UIView]()
for _ in 0 ..< 5 {
array.append(UIView())
//array += [UIView()] //also works
}
AnyIterator
let anyIterator = AnyIterator(UIView.init)
let array = Array(anyIterator.prefix(5))
Sequence
and IteratorProtocol
protocolsstruct ViewSequence: Sequence, IteratorProtocol {
let count: Int
private var index = 0
init(count: Int) {
self.count = count
}
mutating func next() -> UIView? {
guard index < count else { return nil }
defer { index = index.advanced(by: 1) }
return UIView()
}
}
let sequence = ViewSequence(count: 5)
let array = Array(sequence)
Upvotes: 0
Reputation: 72760
In this line:
var views = [UIView?](count: 64, repeatedValue: nil)
you are creating an array of optionals, filled in with nil
- that is what you set with the repeatedValue
parameter. The correct way would be:
var views = [UIView](count: 64, repeatedValue: UIView())
Note however that it creates one UIView
instance only, and assigns it to all 64 elements.
Also, unless there's a specific reason, I don't think you need an array of optionals, so should consider using [UIView]
That said, if you want an array of unique instances, you can use this code:
var views = [UIView]()
for _ in 1...100 {
views.append(UIView())
}
Upvotes: 7
Reputation: 12336
var views = [UIView]()
views.reserveCapacity(100) // not necessary but improves performance just a little bit
for var i = 0; i < 100; i++ {
views.append(UIView())
}
views[0].backgroundColor = UIColor.redColor()
Upvotes: 1