0

My code below is trying to add all of the pics declared in the array above to a for each statement. I tried to do pic[0-14] that is declaring a compile error of fatal error index out of range. I dont know why this is happening. I can imagine i have to do pic[0], pic[1], pic[2] etc.

let pic = (0..<15).map { _ in UIImageView() }

   override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    [pic[0-14]].forEach({
        $0.isUserInteractionEnabled = true
               self.view.addSubview($0)
           })}

1 Answer 1

1

pic[0-14] is trying to do pic[-14], which is out of range. You should do:

pic[0...14].forEach({
    $0.isUserInteractionEnabled = true
    self.view.addSubview($0)
})

Although, I don't see a reason for you to be taking a subrange, so you can do:

pic.forEach({
    $0.isUserInteractionEnabled = true
    self.view.addSubview($0)
})

or

for p in pic {
    p.isUserInteractionEnabled = true
    self.view.addSubview(p)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.