返回

函数构建器的优雅 UIAlertController API

见解分享

前言

UIAlertController 是一个强大的工具,可用于在 iOS 应用程序中呈现警报和操作表。然而,构建和配置 UIAlertController 可能是一个乏味的过程,需要大量的代码。FunctionBuilder 提供了一种简化此过程的方法,从而可以创建更简洁、更易读的代码。

使用 FunctionBuilder

FunctionBuilder 是 Swift 5.1 中引入的一项新特性,它允许我们创建自定义函数类型,这些函数类型可以将函数调用和表达式组合成一个新的值。要使用 FunctionBuilder,我们首先需要创建一个符合 FunctionBuilder 协议的类型。对于 UIAlertController,我们可以创建一个名为 AlertBuilder 的类型:

@_functionBuilder
struct AlertBuilder {
    static func buildBlock(_ actions: UIAlertAction...) -> UIAlertController {
        let alert = UIAlertController()
        alert.actions = actions
        return alert
    }
}

AlertBuilder 类型具有一个名为 buildBlock 的静态函数,该函数接受 UIAlertAction 数组并返回 UIAlertController 实例。这使我们能够通过使用函数调用语法来构建 UIAlertController:

let alert = AlertBuilder {
    UIAlertAction(title: "OK", style: .default, handler: nil)
    UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
}

这比使用标准的 UIAlertController 初始化程序更简洁、更易读。

添加标题和消息

我们可以扩展 AlertBuilder 以支持标题和消息:

extension AlertBuilder {
    static func buildBlock(title: String, message: String, @AlertBuilder actions: () -> UIAlertAction...) -> UIAlertController {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.actions = actions()
        return alert
    }
}

现在,我们可以使用以下语法创建带有标题和消息的 UIAlertController:

let alert = AlertBuilder {
    title: "Warning",
    message: "Are you sure you want to delete this item?",
    UIAlertAction(title: "Yes", style: .destructive, handler: nil),
    UIAlertAction(title: "No", style: .cancel, handler: nil)
}

呈现警报

最后,我们可以扩展 AlertBuilder 以支持呈现警报:

extension AlertBuilder {
    static func buildBlock(presentIn viewController: UIViewController, @AlertBuilder actions: () -> UIAlertAction...) -> UIAlertController {
        let alert = buildBlock(actions: actions())
        viewController.present(alert, animated: true, completion: nil)
        return alert
    }
}

现在,我们可以使用以下语法创建和呈现 UIAlertController:

AlertBuilder {
    title: "Success",
    message: "Item deleted successfully.",
    UIAlertAction(title: "OK", style: .default, handler: nil)
}
.presentIn(viewController: self)

结论

使用 FunctionBuilder,我们可以简化 UIAlertController 的调用,从而构建一个更舒适的 API。这种方法减少了代码量,提高了代码可读性,并使创建定制的 UIAlertController 变得更加容易。随着 Swift 的不断发展,FunctionBuilder 将成为构建更强大、更灵活的 iOS 应用程序的宝贵工具。