Leave a rating/review
It’s time to tackle the next item on our programming to-do list: “Read the value of the slider after the user presses the Hit Me button.”
Before we start working on this, I want to tell you about a very important data type you’ll use in your iOS apps: Strings.
To create a String in Swift, you simply surround some text by quotes.
Behind the scenes, strings are just a sequence of characters. You can imagine them as a bunch of characters hanging on a piece of string, like you see here.
Strings in Swift have a cool feature called string interpolation. That’s just a fancy way of saying that you can put placeholder values inside your string, that are replaced dynamically by code when the app runs.
Imagine you have a string where you want to put a dynamic value inside at runtime. For example, maybe you want to say Hello, and then the name of the user of the app.
To do this, wherever you want the value to appear in your string, you put a backslash, and two parenthesis. Inside the parenthesis, you put some code that evaluates to the value to display.
In this example, if name is set to Ozma, at runtime the string will become “Hello, Ozma”.
Let’s try this out by making our app print out the value of the slider, inside a string.
All right, so what wanna do is we want to show current value of the slider inside this alert message here instead of, this is my first alert.
We want to say, the slider’s value is, and then put it in the slider value.
We can do that by using String Interpolation. And the way that works is we put a backslash and two parentheses and inside these parentheses, we can put a reference to any code that evaluates to a value that can go in a string. In our case, we’ll use slider.value.
Text("\(sliderValue)")
This takes whatever the slider’s current value is and puts it into that string.
I’m just going to make it a sentence that says “The slider’s value is” with a period at the end.
message: Text("The slider's value is \(sliderValue)."),
Try it out right in the canvas!
Tap “hit me”, and that sets the sliders value to… 50 points and a lot of zeros.
This is great, but this level of precision is way more than we need.
It would be nice to show this value as a whole number, which is also known as the integer, rather than having all of these decimal points.
So how do we fix this? Well, you’ll find that out in the next episode.