Your First iOS & SwiftUI App: An App from Scratch

Feb 13 2023 · Swift 5.7, iOS 16, Xcode 14

Part 3: Coding in Swift

26. Challenge: Calculate the Difference

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 25. If / Else Statements Next episode: 27. Variables & Constants

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

In the previous challenge I mentioned that there's another way to calculate the difference that requires fewer lines of code and that's the subject of this challenge. The new algorithm looks like this. First, subtract the target value from the slider's value. Then if the result is a negative number, multiply it by -1 to make it a positive number. At this point, pause the video and try changing the difference calculation to this new algorithm. Then keep watching to compare your work to my solution. That's it, good luck! (soft upbeat music) All right, I'm going to delete our old if else statement here and instead we're just going to say difference = target - sliderValue. Now this might be negative, right, because what if the target is 50 and sliderValue is 55? That would be -5. So we're going to say if difference < 0, then we're going to say difference = difference * -1. There's a couple of shortcuts to doing this line in Swift and I'll put two of them in the comments here. You can make a comment in your code with two forward slashes. Any code after this on the line will not run, it's just for your reference. So instead of this we could say difference *= -1 These two lines are exactly the same. The second one is just a shortcut way to type it because I haven't had to type difference twice. And actually there's another shortcut you can use here. You can say difference = -difference. All of those, they all effectively work the same. I'm just gonna leave it as this first one for now and delete the comments. You are welcome to keep them for your own reference. Alright, so now I'm gonna hit CMD+U. First of all, this is one of the benefits of unit tests. We can make sure we didn't break anything so if our unit tests pass, our code should be good. I switched over to the test navigator and we got greens, so that's looking good, and I'm just going to run the app just to manually test as well. Give it my best guess. Now it looks right, nice work.