我尝试从函数中返回String
,但是出现错误“使用未解析的标识符nameOfFlower”。这是我的功能:
func detectFlower(image: CIImage) -> String {
guard let model = try? VNCoreMLModel(for: FlowerModels().model) else {
fatalError("Cannot import a model.")
}
let request = VNCoreMLRequest(model: model) { (request, error) in
let classification = request.results?.first as? VNClassificationObservation
var nameOfFlower = String(classification?.identifier ?? "Unexpected type")
}
let handler = VNImageRequestHandler(ciImage: image)
do {
try handler.perform([request])
} catch {
print(error)
}
return nameOfFlower
}
代码有什么问题?
答案 0 :(得分:2)
它的异步代码..所以使用闭包作为完成块
func detectFlower(image: CIImage,completion: @escaping (_ getString:String?,_ error:Error?)-> Void) {
guard let model = try? VNCoreMLModel(for: FlowerModels().model) else {
fatalError("Cannot import a model.")
}
let request = VNCoreMLRequest(model: model) { (request, error) in
let classification = request.results?.first as? VNClassificationObservation
var nameOfFlower = String(classification?.identifier ?? "Unexpected type")
completion(nameOfFlower,nil)
}
let handler = VNImageRequestHandler(ciImage: image)
do {
try handler.perform([request])
} catch {
print(error)
completion(nil,error)
}
}
使用方法
detectFlower(image: yourImage) { (flowerString, error) in
// you get optional flower string here
}