Array of UIViews
Is there a way to create an array of UIViews?
I tried bot, I cannot add values
var views = [UIView?](count: 64, repeatedValue: nil)
The result is nil
views[0]?.backgroundColor = UIColor.redColor()
I have also tried
var views = NSMutableArray()
for (var a = 0; a<100; a++){
views[a] = UIView()
}
views[0].backgroundColor = UIColor.redColor() // fails
source to share
In this line:
var views = [UIView?](count: 64, repeatedValue: nil)
you create an array of options populated with nil
- this is what you set with the parameter repeatedValue
. The right way:
var views = [UIView](count: 64, repeatedValue: UIView())
Note that it only creates one instance UIView
and assigns it to all 64 elements. Also, unless there is a specific reason, I don't think you need an array of options, so you should consider using[UIView]
However, if you want an array of unique instances, you can use this code:
var views = [UIView]()
for _ in 1...100 {
views.append(UIView())
}
source to share
With Swift 4, you can use one of the following ways to solve your problem.
# 1. Using Range
andmap(_:)
let range = 0 ... 5
let array = range.map { _ in UIView() }
# 2. Using Range
and for loop
var array = [UIView]()
for _ in 0 ..< 5 {
array.append(UIView())
//array += [UIView()] //also works
}
# 3. Using AnyIterator
let anyIterator = AnyIterator(UIView.init)
let array = Array(anyIterator.prefix(5))
# 4. Using a custom framework that conforms to protocols Sequence
andIteratorProtocol
struct 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)
source to share