Using "I" in "accessible" access to properties before super.init initializes itself

I have this code

import UIKit

class CardView: UIView {

    @IBOutlet var imageView: UIImageView!

    init(imageView: UIImageView) {
        self.imageView = imageView
        super.init(frame: CGRect(x: 0, y:0, width: self.frame.size.width, height: self.frame.size.height))
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

I get an error in the line:

super.init(frame: CGRect(x: 0, y:0, width: self.frame.size.width, height: self.frame.size.height))

Error says Use of 'self' in property access 'frame' before super.init initializes self

I do not know how to solve this.

Please note that I am from objective background C and recently started to learn fast.

+4
source share
1 answer

You must call super.init()before accessing selfthe method init():

init(imageView: UIImageView) {
    self.imageView = imageView /*you are accessing self here before calling super init*/
    super.init(frame: CGRect(x: 0, y:0, width: self.frame.size.width /* here also*/, height: self.frame.size.height))
}

Change it to:

init(imageView: UIImageView) {
    super.init(frame: CGRect(origin: CGPoint.zero, size: imageView.frame.size))
    self.imageView = imageView 
}
+5
source

Source: https://habr.com/ru/post/1667429/


All Articles