Sarah Stevens
Sarah Stevens

Reputation: 231

Array of UIViews

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

Answers (3)

Imanou Petit
Imanou Petit

Reputation: 92489

With Swift 4, you can use one of the following ways in order to solve your problem.


#1. Using Range and map(_:)

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 struct that conforms to Sequence and IteratorProtocol protocols

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)

Upvotes: 0

Antonio
Antonio

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

vbezhenar
vbezhenar

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

Related Questions