Search code examples
swiftgoogle-mlkitfirebase-mlkitapple-vision

How do I extract the label with the highest confidence value and print it out in Swift?


private func showResults(_ results: [(label: String, confidence: 
Float)]?) {
    var resultsText = Constants.failedToDetectObjectsMessage
    if let results = results {
      resultsText = results.reduce("") { (resultString, result) -> 
String in
        let (label, confidence) = result
        return resultString + "\(label): \(String(describing: 
confidence))\n"
      }
    }
    resultsAlertController.message = resultsText
    resultsAlertController.popoverPresentationController?.sourceRect = self.annotationOverlayView.frame
    resultsAlertController.popoverPresentationController?.sourceView = self.annotationOverlayView
    present(resultsAlertController, animated: true, completion: nil)
    print(resultsText)
}

This is the sample code that I have tried. How do i extract the label with the highest confidence value and print it out?


Solution

  • The way to know which label has the highest confidence level is to call max(by:) on the results array. See https://developer.apple.com/documentation/swift/sequence/2906531-max

    private func showResults(_ results: [(label: String, confidence: Float)]?) {
        if let results = results {
            let biggest = results.max { $0.confidence < $1.confidence }
            if let biggest = biggest {
                let (label, confidence) = biggest
                // ...
            }
        }
    }