From the course: Programming for Non-programmers: iOS 17 and Swift 5

Unlock this course with a free trial

Join today to access over 24,400 courses taught by industry experts.

Using a method as a variable

Using a method as a variable

- [Instructor] Swift actually allows you to pass in methods as parameters and that's what we're going to look at here. Now, why might you want to do that? Let's go over to our button grid and take a look at our layout. So we have all of these different buttons that do different things. The clear button should clear the value at the top of the calculator. The numeric buttons are used for capturing input. Then we have the mathematical operator buttons, like the plus and the minus and the multiply button. And then we have the equals button. So each one of these has something different that it does. The numeric buttons are generally the same. So we need some way of being able to say that for this particular button, run this method when it's clicked, and for this other button, run this method. And the one way to handle that is to pass in the method that we want to run as a parameter when creating our buttons. That's how we're going to handle it in this case. So let's go over to…

Contents