1

I'm working on a swift project where I create a custom keyboard. In my ViewController, I store and mutate an array of UIImages. Then, in my Keyboard module in my keyboardViewcontroller.swift I would like to use the data I have in this array to create buttons. However, when I try to access the array in KeyBoardViewController it seems to give me an empty array and throws an index out of bounds error. What is strange to me is that in ViewController I print out the size of my array and it is definitely not empty. Here is how I'm storing the array:

import UIKit
class Main {
    var pics :[UIImage]
    init(pics : [UIImage]) {
        self.pics = [UIImage]()
    }
}
var instance = Main(pics: [UIImage]())

In ViewController I mutate it with instance.pics.append...

In my KeyboardViewController:

for image in instance.pics {
...
}

Why would this show as an empty array in KeyboardViewController? Thanks

3
  • 2
    Why are you passing a parameter that you ignore? Commented Dec 28, 2015 at 1:16
  • Exactly. Instead of asigning the passed pics argument to self.pics, you are assigning a new, empty array ([UIImage]()). Commented Dec 28, 2015 at 1:59
  • Incidentally, the argument passed to the initializer also is an empty array of UIImage. What would you expect to happen? Commented Dec 28, 2015 at 2:00

1 Answer 1

1

Rather than assigning an empty array of UIImage objects, the following will set the internal array variable to be a copy of the myPics array.

import UIKit

class Main {
    var pics: [UIImage]
    init(pics: [UIImage]) {
        self.pics = pics
    }
}

var instance = Main(pics: myPics)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! this looks like what I was looking for. one more question though, what is myPics? Is this an array I should create elsewhere? If I try to create an array in ViewController called myPics and say Main(pics: myPics) it says myPics not found
If you have an existing array of UIImages that you want to save in the Main class, then that would be myPics. Otherwise, create a Main init that simply initialises pics as an empty array.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.