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
From the course: Programming for Non-programmers: iOS 17 and Swift 5
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…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
-
-
-
(Locked)
Understanding methods5m 30s
-
(Locked)
Using methods3m 47s
-
(Locked)
Running code when a button is pressed3m 43s
-
(Locked)
Using a method as a variable4m 46s
-
(Locked)
Passing parameters to method variables3m 24s
-
(Locked)
SwiftUI binding5m 21s
-
(Locked)
Using different methods to handle different events3m 2s
-
(Locked)
Challenge: Create methods for the equal button52s
-
(Locked)
Solution: Create methods for the equal button48s
-
(Locked)
-
-
-