swift 在另一个函数中包装函数

swift wrap function in another function

我有一个 class 来检查我在这里找到的互联网连接:

在我的方法中我使用它:

     override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        if Reachability.isConnectedToNetwork() == false {
            let alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
            alert.show()
            return
        }
    }

但是我可以做一个装饰器或类似的东西来写这样的东西吗:

@check_internet_connection
override func viewWillAppear(animated: Bool) {

}

或者例如将它用于 class 中的所有方法:

@check_internet_connection
class MyClass: UIViewController {
    ...
}

继承方法

您可以创建 ReachabilityAwareViewController 作为基础 class。

class ReachabilityAwareViewController: UIViewController{

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        if Reachability.isConnectedToNetwork() == false {
            // your code goes here
        }
    }
}

并创建继承 ReachabilityAwareViewController.

所有行为的子 class
class myViewController: ReachabilityAwareViewController{
    // ..
}

组合方法

这种方法看起来更像装饰器。使用协议扩展

protocol ReachabilityAware{
    func checkReachibility()
}

extension ReachabilityAware where Self: UIViewController{

    func checkReachibility(){
        if Reachability.isConnectedToNetwork() == false {
            let alertController = UIAlertController(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", preferredStyle: .Alert)
            let okAction = UIAlertAction(title: "OK", style: .Cancel){ action in }
            alertController.addAction(okAction)
            presentViewController(alertController, animated: true, completion: nil)
        }
    }
}

class myViewController: UIViewController, ReachabilityAware{

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        checkReachibility()
    }
}

在 Swift 中,这些被称为 Attributes。目前(从 Swift 2.1 开始),您无法定义自己的。

为什么不写一个全局函数来处理这个问题?

// In global scope
func check_internet_connection() -> Bool {
    if Reachability.isConnectedToNetwork() == false {
        let alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
        alert.show()
        return false
    } else {
        return true
    }
}

…

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    if !check_internet_connection() { return }
}