Your First iOS & SwiftUI App: An App from Scratch

Jan 11 2022 · Swift 5.5, iOS 15, Xcode 13

Part 2: SwiftUI Data

15. Strings

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: 14. SwiftUI Bindings Next episode: 16. Variables
Transcript: 15. Strings

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 Ray, at runtime the string will become “Hello, Ray”.

Let’s try this out by making our app print out the value of the slider, inside a string.

Change alert text to:

message: Text("The slider's value is \(self.sliderValue)."),

Build & run.

We’re now printing the value of the slider, but currently it’s displaying the value with an annoying level of precision. It would be nice to print this out as a whole number - also known as an Integer - rather than having decimal points. How do we fix this?

Well, you’ll find out in the next episode.