self在swift项目中不可用



我正在尝试在swift中运行图像比较。然而,我得到了一个错误,状态为Cannot use instance member 'featureprintObservationForImage' within property initializer; property initializers run before 'self' is available。则错误出现在CCD_ 2的第一行上。

为什么self在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!)

}

featureprintObservationForImage函数的右大括号后的所有代码都不在任何函数或闭包内。你不能那样做。(该代码不仅仅是可变标记。您有函数调用,这在函数之外是不合法的。(

可以创建一种称为计算属性的东西,在其中提供一个闭包,每次从属性中读取值时都会调用该闭包。

您不能在变量声明中访问self

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` 
}
}

相关内容

  • 没有找到相关文章

最新更新