【swift tip】当方法成为一级公民后

278 阅读1分钟

当函数成为一级公民后,我们可以将函数当作变量来使用,也可以当作参数传给另一个函数,这是函数式编程的基石,这里列举一级公民函数first-class-functions在日常编程中带来的惊喜点。

1. 简化高阶函数中闭包的使用

var view = UIView()
var subviews = [UIButton(),UILabel(),UIImageView()]

// use closure
subviews.forEach { subview in
    view.addSubview(subview)
}

// use first-class-method
// made code more clear and readable
subviews.forEach(view.addSubview)
let strings = ["www.baidu.com", "apple.com"]

// use closure
strings.compactMap { string -> URL in
    return URL.init(fileURLWithPath: string)
}

//use first-class-method
strings.compactMap(URL.init)

2.替代closure中weak self的调用

class ProductViewController: UIViewController {
    ...
    override func viewDidLoad() {
        super.viewDidLoad()

        buyButton.handler = { [weak self] in
            guard let self = self else {
                return
            }
            self.productManager.startCheckout(for: self.product)
        }
    }
}

// use a combine function for applying a value to any function or closure

func combine<A, B>(_ value: A,
    with closure: @escaping (A) -> B) -> () -> B {
        return { closure(value) }
}

// use combine to refactor the handler
class ProductViewController: UIViewController {
    ...
    override func viewDidLoad() {
        super.viewDidLoad()
        buyButton.handler = combine(product,with: productManager.startCheckout)
    }
}