0

I've tried to return String from my function, but I get error "Use of unresolved identifier nameOfFlower". Here's my function:

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
       }

What is wrong with code?

6
  • Don't leave us hanging. What was the rest of the error message? Please post exactly what you get. Commented May 14, 2020 at 19:20
  • you need to retur completion block instead of return Commented May 14, 2020 at 19:25
  • 2
    its async code .. so use closure Commented May 14, 2020 at 19:25
  • @tadman I'm sorry, I already edited code. Commented May 14, 2020 at 19:30
  • 1
    Does this answer your question? Returning data from async call in Swift function Commented May 14, 2020 at 20:04

1 Answer 1

2

Its async code .. so use closure as completion block

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


    }

How to use

     detectFlower(image: yourImage) { (flowerString, error) in
                // you get optional flower string here
            }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.