Search code examples
iosswiftdecoratorword-wrap

swift wrap function in another function


I have a class to check internet connection that i found here: Check for internet connection with Swift

In my methods i use it:

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

but can i make a decorator or something to write something like:

@check_internet_connection
override func viewWillAppear(animated: Bool) {

}

or for example use it for all methods in class:

@check_internet_connection
class MyClass: UIViewController {
    ...
}

Solution

  • In Swift these are called Attributes. Currently (as of Swift 2.1), you cannot define your own.

    Why not write a global function to handle this?

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