升级Xcode 14后调用AirPrint present函数出现未使用Bool返回值警告
Xcode 14中AirPrint present函数出现“未使用Bool返回值”警告的解决方法
升级至Xcode 14后,调用UIPrintInteractionController的present(animated:completionHandler:)实现PDF打印时,出现“Result of call to function returning 'Bool' is unused”警告,这是因为Xcode 14默认启用了更严格的Swift检查规则(对应Swift 6的相关改动),而Xcode 13及之前版本不会触发该警告。
问题原因
present(animated:completionHandler:)方法本身会返回一个Bool值,用于标识打印控制器是否成功弹出。在旧版Swift规则中,未使用这个返回值不会触发警告,但Xcode 14强化了对未使用返回值的检查,因此出现该提示。
解决方法
方法1:明确忽略返回值
如果不需要判断控制器是否弹出,直接用下划线_接收返回值,告知编译器我们有意忽略该结果:
/// Prints the PDF file using airprint func printPDF() { let pdfFileURL = FileManager.default.temporaryDirectory.appendingPathComponent( "Filename.pdf" ) let printController = UIPrintInteractionController.shared let printInfo = UIPrintInfo(dictionary: nil) printInfo.jobName = "Print PDF" printInfo.outputType = .general printController.printInfo = printInfo printController.printingItem = pdfFileURL // 用_接收返回值,消除警告 _ = printController.present(animated: true) { (_, isPrinted, error) in if let error = error { print("Print Failed: \(error.localizedDescription)") } else { print(isPrinted ? "Print Success" : "Print Cancelled") } } }
方法2:利用返回值做额外逻辑处理
如果需要判断打印控制器是否成功弹出,可以接收返回值并添加对应处理逻辑:
/// Prints the PDF file using airprint func printPDF() { let pdfFileURL = FileManager.default.temporaryDirectory.appendingPathComponent( "Filename.pdf" ) let printController = UIPrintInteractionController.shared let printInfo = UIPrintInfo(dictionary: nil) printInfo.jobName = "Print PDF" printInfo.outputType = .general printController.printInfo = printInfo printController.printingItem = pdfFileURL // 接收返回值,判断控制器是否弹出成功 let didPresentSuccessfully = printController.present(animated: true) { (_, isPrinted, error) in if let error = error { print("Print Failed: \(error.localizedDescription)") } else { print(isPrinted ? "Print Success" : "Print Cancelled") } } if !didPresentSuccessfully { print("打印控制器无法弹出,请检查设备AirPrint支持状态或可用打印机") } }
另外,原代码中的错误处理逻辑可以优化为提前解包error,让代码逻辑更简洁清晰,避免冗余判断。
内容的提问来源于stack exchange,提问作者kittonian
相关产品推荐
相关产品推荐

