[SOLVED] self is not available in swift project


I am trying to run an image comparison in swift. However i am getting an error that states Cannot use instance member 'featureprintObservationForImage' within property initializer; property initializers run before 'self' is available.
the error appears on the first of the let lines.

Why would self not already available within the ViewController?

import UIKit
import Vision

class ViewController: UIViewController {

    override func viewDidLoad() {
        // Do any additional setup after loading the view.

    func featureprintObservationForImage(atURL url: URL) -> VNFeaturePrintObservation? {
        let requestHandler = VNImageRequestHandler(url: url, options: [:])
        let request = VNGenerateImageFeaturePrintRequest()
        do {
          try requestHandler.perform([request])
          return request.results?.first as? VNFeaturePrintObservation
        } catch {
          print("Vision error: \(error)")
          return nil
    let apple1 = featureprintObservationForImage(atURL:Bundle.main.url(forResource:"apple1", withExtension: "jpg")!)
    let apple2 = featureprintObservationForImage(atURL: Bundle.main.url(forResource:"apple2", withExtension: "jpg")!)
    let pear = featureprintObservationForImage(atURL: Bundle.main.url(forResource:"pear", withExtension: "jpg")!)
    var distance = Float(0)
    try apple1!.computeDistance(&distance, to: apple2!)
    var distance2 = Float(0)
    try apple1!.computeDistance(&distance2, to: pear!)


All the code after the closing brace for your featureprintObservationForImage function is not inside any function or closure. You can’t do that. (That code is not just variable decalrations. You have function calls, which is not legal outside of a function.)

You can create something called computed properties, where you provide a closure that gets invoked each time you read a value from the property.

Answered By – Duncan C

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *