【发布时间】:2020-09-09 00:18:23
【问题描述】:
我很好奇是否有办法简化/使闭包可重用?我在这里问了一个更深入的问题:Swift - Refactoring code. Closure and inout? 和有问题的代码相同。
我想做的是让这个闭包变成一行:
self.feedbackManager?.send(on: self) { [weak self] result in
switch result {
case .failure(let error):
print("error: ", error.localizedDescription)
case .success(_):
print("Success")
}
self?.feedbackManager = nil
}
feedbackManager 是一个类的实例,它在self.viewController 上呈现一个MFMailComposeViewController。 result 是 MFMailComposeResult。这是闭包中的result。
所以理想情况下,它可以被称为这样的东西?
self.feedbackManager?.send(on: self) { switchResultClosure }
编辑:结果
实施:
let feedback = Feedback(subject: "subject", body: "body", footer: "footer")
sendEmail(with: feedback, on: self)
类:
import UIKit
import MessageUI
struct Feedback {
let recipients = [R.App.Contact.email]
let subject: String
let body: String
let footer: String
}
enum SendStatus: Int {
case sent, cancelled, failed, notSupported, saved
}
protocol FeedbackProtocol {
func sendEmail(with feedback: Feedback, on viewController: UIViewController)
}
extension FeedbackProtocol {
func sendEmail(with feedback: Feedback, on viewController: UIViewController) {
print("protocol FeedbackController: sendEmail()")
ShareController.shared.sendMailToRecipients(with: feedback, on: viewController) { (SendStatus) in
print("SendStatus: ", SendStatus)
}
}
}
final class ShareController: NSObject {
static var shared = ShareController()
var completionBlock: ((SendStatus) -> Void)?
private override init() { }
}
extension ShareController: MFMailComposeViewControllerDelegate {
func sendMailToRecipients(with feedback: Feedback, on viewController: UIViewController, block: @escaping (SendStatus) -> Void) {
print("sendMailToRecipients()")
guard MFMailComposeViewController.canSendMail() else {
block(.notSupported)
return
}
var appVersion = ""
if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
appVersion = version
}
completionBlock = block
let mailController = MFMailComposeViewController()
mailController.mailComposeDelegate = self
mailController.mailComposeDelegate = self
mailController.setToRecipients(feedback.recipients)
mailController.setSubject(feedback.subject)
mailController.setMessageBody((feedback.body), isHTML: true)
DispatchQueue.main.async {
viewController.present(mailController, animated: true, completion: nil)
}
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
print("mailComposeController(): ShareVC")
controller.dismiss(animated: true)
switch result {
case .sent: completionBlock?(.sent)
case .cancelled: completionBlock?(.cancelled)
case .failed: completionBlock?(.failed)
case .saved: completionBlock?(.saved)
default: break
}
}
}
【问题讨论】:
-
你不能把switch语句提取到一个函数中并调用那个函数吗?或者你想这样做,但不知道怎么做?
-
我想这样做,但不知道怎么做。
标签: ios swift closures mfmailcomposeviewcontroller