Cannot Use Instance Member Within Property initializer

I'm trying to encode an image when this error occurred

Cannot use instance member 'image' within property initializer; property initializers run before 'self' is available

And having not ran into this before and the error not having a fix button like others, I was puzzled so I came here for help

import UIKit

class ViewController: UIViewController {

  @IBOutlet weak var myImageView: UIImageView!
   
  let image = UIImage(named: "image.png")
  let imageData:NSData = UIImagePNGRepresentation(image!)! as NSData //Error is here!
   
  override func viewDidLoad() {
    super.viewDidLoad()
  }


}
Answered by DTS Engineer in 723328022

The error message tells you what is wrong. Initialization of instance properties happens (conceptually, at least) before the class's init has run, which means that self is not yet available.

The usual solution in this case (UIViewController), is to set the value in viewDidLoad, which means you'll need to use an implicitly unwrapped optional (IUO) for the property:

  …
  let imageData: NSData!
   
  override func viewDidLoad() {
    super.viewDidLoad()
    imageData = UIImagePNGRepresentation(image!)! as NSData
  }
  …

Note that this can be a little problematic if the final value of imageData must be available before viewDidLoad has run, but typically this won't be a problem.

Accepted Answer

The error message tells you what is wrong. Initialization of instance properties happens (conceptually, at least) before the class's init has run, which means that self is not yet available.

The usual solution in this case (UIViewController), is to set the value in viewDidLoad, which means you'll need to use an implicitly unwrapped optional (IUO) for the property:

  …
  let imageData: NSData!
   
  override func viewDidLoad() {
    super.viewDidLoad()
    imageData = UIImagePNGRepresentation(image!)! as NSData
  }
  …

Note that this can be a little problematic if the final value of imageData must be available before viewDidLoad has run, but typically this won't be a problem.

Cannot Use Instance Member Within Property initializer
 
 
Q