ineedhelp
ineedhelp

Reputation: 31

Type has no member

I'm new to swift and I'm trying to create a very simple app but for some reason, the variables are not working.

I'm not really sure what the problem is but I've tried changing var to let.

class ImageViewController: ViewController {

var blocks = [Block(size: 100, centerX: 100, centerY: 100, code: "1", color: image.colorDic["1"]!)]
var codes = ["1"]
var colors = [UIColor(named: "Red")]

//create image
var image = Image(blocksArray: blocks, code: codes, color: colors)

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .blue
    title = "Title"
    for block in image.blocksArray{
        view.addSubview(block.block)
    }
    // Do any additional setup after loading the view.
}

On the line where I create the image, I get an error that says

"Type 'ImageViewController' has no member 'blocks'"

Also, right under the line where I create 'colors' I'm also getting

"Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffee74cbf48)"

Upvotes: 1

Views: 1055

Answers (1)

Mussa Charles
Mussa Charles

Reputation: 4442

your property image access the block property before they are both initilized, to fix your problem your variable "image" should be flagged as lazy variable, meaning it will be initilized after the other properties have been initilized hence it is safe to access those other properties.

More about lazy properties

The official Swift documentation says,

"Lazy properties are useful when the initial value for a property is dependent on outside factors whose values are not known until after an instance’s initialization is complete."

You can read more about lazy properties here: - Swift Properties Official documentation

Here is how to do it: -

  lazy var image: Image = {
    return Image(blocksArray: blocks, code: codes, color: colors)
}()

for the case of colors part, I think it is a good practice to avoid typing strings when initializing especially for simple colors like yours and use the enum versions. Change it to this : -

var colors = [UIColor.red]

or this: -

var colors: [UIColor] = [.red]

Upvotes: 0

Related Questions