Introduction to Swift

Apr 24 2024 · Swift 5.10, iOS 17, Xcode 15

Lesson 01: Swift Basics

Strings Demo

Episode complete

Play next episode

Next
Transcript

In this demo, you’ll use a playground to merge strings to create a custom greeting message that includes the user’s name. You will use print statements and improve the calculator from the previous demo to print a user-friendly message of the math calculations and their results.

Open Xcode on your Mac, select FileNewPlayground. Select Blank and choose any location to save the new file, but give it the name Lesson1Demo2 so you can refer to it any time later. Remove the existing code before you start.

For the first part of this demo, you’ll create a custom greeting message that includes a name. The message should be like this: "Hello Raymond, it's good to see you today". Replace the name “Raymond” with any name you want.

To start, create three string constants, one for the text before the name, one for the name, and the third for the text after the name:

let welcomeMessage_part1 = "Hello "
let username = "Raymond"
let welcomeMessage_part2 = ", it's good to see you today."

Remember: You can change the value of username to any other name you want. Notice that the end of welcomeMessage_part1 and the beginning of welcomeMessage_part2 include the separators before and after the name. Swift won’t add spaces or punctuation on its own when you merge strings.

To build the message, you’ll create a new constant with the value from merging, aka concatenating, the three strings:

let message = welcomeMessage_part1 + username + welcomeMessage_part2

Run the playground and observe the values in the right pane.

Next, print the value of message using print statement:

print(message)

Run the playground again and open the drawer on the bottom of the playground window if it’s not already open. Notice the text written there.

This is where all the messages you print will appear.

Now, print the length of message:

print(message.count)

Run the playground and notice the number that is printed.

Next, print the uppercase and lowercase versions of message:

print(message.uppercased())
print(message.lowercased())

Then, print an altered version of the message that replaces the word “Hello” with “Greetings”:

print(message.replacing("Hello", with: "Greetings"))

Run the playground and look at the printed messages at the bottom. You can also compare them with the values on the right.

Remember that this right pane is unique to playgrounds and doesn’t exist when you’re writing an iOS or macOS app. However, you can rely on print statements to show you variable values in the console pane as you’re working. Just be sure to delete them when you finish writing your app.

The last print message you’ll try is to use \() for the username and build the message without concatenating three strings:

let message2 = "Hello \(username), it's good to see you today."
print(message2)

message and message2 are identical. The only difference was how you constructed the string, and both approaches are acceptable. The main difference is how the code looks and how easy it is to understand.

In the second part of the demo, you’ll improve the calculator from the last demo. You don’t need to open the old playground again; you can write parts of it again to help you remember it.

Create two constants — int1 and int2 — with initial values of 10 and 5:

let int1 = 10
let int2 = 5

Now, create four new constants that store the sum, subtraction, multiplication, and division. Leave an empty line between them:

let intSum = int1 + int2

let intSubtract = int1 - int2

let intMultiply = int1 * int2

let intDivide = int1 / int2

You’ll print a message in the console for each of the math operations to include the data type, operation name, inputs, and results. The message for the sum operation is:

print("Integer sum of \(int1) and \(int2) is: \(intSum)")

Run the playground and see your new message in the bottom, console pane of the playground. Expand it if it’s not open.

Using the same pattern as before, add the other three messages:

print("Integer subtraction of \(int1) and \(int2) is: \(intSubtract)")

print("Integer multiplication of \(int1) and \(int2) is: \(intMultiply)")

print("Integer division of \(int1) and \(int2) is: \(intDivide)")

Run the playground to see the results.

For Float and Double, declare two constants for each with the values 11 and 6 and only write the division operation; you can skip the other three:

let float1: Float = 11
let float2: Float = 6

let floatDivide = float1 / float2

let double1 = 11.0
let double2 = 6.0

let doubleDivide = double1 / double2

Just like before, print a user-friendly message for the division operation:

print("Floating-point division of \(float1) and \(float2) is: \(floatDivide)")

print("Double-precision floating-point division of \(double1) and \(double2) is: \(doubleDivide)")

Run the playground to see the results.

Notice how doubleDivide has many more decimal points than floatDivide and the conversion to string didn’t skip any of them.

Using string interpolation, which is the backslash and curved brackets \(), makes creating strings very easy to read and understand. If you were to convert each number to a string, then construct the string by concatenating different parts of it together, the code wouldn’t have looked as organized as it is now.

This is one of the great things about the Swift language: It provides ways to do things in a much cleaner way that makes it effortless to read and understand code that is performing complex operations.

As you gain experience writing code, you’ll learn that it’s not only about writing code to perform a task, but it’s also about keeping code as organized as possible so it’s easy for others to work with you. It’s even for you to understand your own code when you want to return back to it after some time. It’s hard to remember what you were thinking of when you wrote it, so it’ll feel like you’re looking at it for the first time.

In the next and final part of this lesson, you’ll write some code that calculates the first few elements of the Fibonacci sequence.

See forum comments
Cinema mode Download course materials from Github
Previous: Strings Next: Arrays