Search code examples
iosswiftuiviewswift4

Swift 4 : Adding UIView into the array programmatically with for loop


I'm using scrollView paging and I want to add UIViews into the scrollView programmatically with for loop. But I guess I'm missing something.

Here is my code :

func createSlide() ->[Slide]{
    for i in 0..<datas.count{
        slideAll?.append(Bundle.main.loadNibNamed("ViewTest", owner: self, options: nil)?.first as! Slide)

        slideAll![i].testLabel.text = datas[i]
    }

    return slideAll!

}

Is this possible that I can add UIView like that? If I can, how can I fix this code piece?

Edit :

I realized that I initialize the slideAll with no value on the top like that :

var slideAll:[Slide]?

How can I initialize this correctly? Should I initialize this on the function?


Solution

  • Instead of this line:

    var slideAll:[Slide]?
    

    say this:

    var slideAll = [Slide]()
    

    Then remove the Optional unwrap notations from your references to slideAll in the rest of the code.