skip to Main Content

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() {
        super.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!)
    
}

2

Answers


  1. 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.

    Login or Signup to reply.
  2. You can’t access self in variable declaration.

    import UIKit
    import Vision
    
    class ViewController: UIViewController {
        
        var testVeriable : Int = 0//hear you cannot access `self`
        
        func test(){
            self.testVeriable = 1// In function you can access class variable or function using `self` 
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search