Skip to content

iOS Property as Function

Platform Language License

You can write a property as func in swift.

Example:

class ViewController: UIViewController {
  //MARK: Declaration
  var aFunctionProperty: (() -> Void)?
  override func viewDidLoad() {
    super.viewDidLoad()
    //Completion Block
    aFunctionProperty = { 
      print("Success")
    }
  }
}

To call the property I have written inside button action, you can try inside any API call's or button action or tap-gesture any where you need.

extension ViewController {
  @IBAction func buttonAction(_ sender: UIButton) { 
  //Call the function using optional chaining.
  //if `aFunctionProperty` is nil or has value, it will work.
  aFunctionProperty?()
  } 
}

"Closures are self-contained blocks of functionality that can be passed around and used in your code."
-Apple

Some Examples:

  1. You can add some parameters to pass inside completion block's.
  2. I have tried using Result of Swift 5.
class ViewController: UIViewController {
  //MARK: Declaration
  var aFunctionProperty: ((Result) -> Void)? 

  override func viewDidLoad() {
    super.viewDidLoad()
    //Completion Block
    aFunctionProperty = { (result) in
      switch result {
      case .success(true):          
        print("Success")        
      default:               
        print("Fail")
      }
    }
  }
}
extension ViewController {
  @IBAction func buttonAction(_ sender: UIButton) {     
    //Call the function using optional chaining.
    //if `aFunctionProperty` is nil or has value, it will work.
    aFunctionProperty?(.success(true))
    aFunctionProperty?(.success(false))
  }
}

You can also assign a function to a property.

Example:

class ViewController: UIViewController {
  //MARK: Declaration
  var aFunctionProperty: (() -> Void)?
}

In some other class you can do assign & call like:

class Foo {
  //Creating Object for Viewcontroller
  let viewObj = ViewController()
  //Creating `success` func
  func success() {
    print("Success")
  }
  //Creating `boo` func
  func boo () {
    //Assigning a `func` to a `aFunctionProperty`
    viewObj.aFunctionProperty = success
   //Call the Property where you need to call.
   viewObj.aFunctionProperty?()
  }
}

Now you can call a single function.

let foo = Foo()
foo.boo()

Try it in you code, it will work like awesome.

Let's grow together 🌱

Cheers 🍻