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

时间:2015-10-24 12:58:31

标签: ios swift decorator wrapping

我有一个班级来检查我在这里找到的互联网连接:Check for internet connection with Swift

在我的方法中,我使用它:

     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) {

}

或者例如将它用于课堂上的所有方法:

@check_internet_connection
class MyClass: UIViewController {
    ...
}

2 个答案:

答案 0 :(得分:0)

继承方法

您可以将ReachabilityAwareViewController创建为基类。

class ReachabilityAwareViewController: UIViewController{

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

并创建继承ReachabilityAwareViewController的所有行为的子类。

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()
    }
}

答案 1 :(得分:0)

在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 }
}