DEV Community

Cover image for Intro to Swift: Strings and Arithmetic
Joshua Rutkowski
Joshua Rutkowski

Posted on

Intro to Swift: Strings and Arithmetic

In this lesson, you’ll learn some of the fundamentals for using strings and arithmetic in Swift.

Objectives:

  • Learn to create static strings using string literal syntax
  • Learn to concatenate strings
  • Learn to use string interpolation to include variable values in a string
  • Learn to use arithmetic operators to add, subtract, multiply, and divide variables
  • Learn to use comments to make code easier to understand

Note: This lessons roughly follows along Lambda School's iOS 101 precourse work. For additional information on Lambda School's iOS Development course, click here.

Learn to create static strings using string literal syntax

A string is a series of characters, such as "hello, world" or "starship". 🚀

Swift strings are represented by the String type. The simplest way to create a string in Swift is to use a string literal. A string literal is a sequence of characters surrounded by double quotation marks ("). For example:

let name = "Benjamin Sisko"

Note that Swift infers a type of String for the name constant because it’s initialized with a string literal value. In the above example, "Benjamin Sisko" is a string literal. You use string literals to initialize string constants or variables, but you can also use them anywhere a string is required.

Multi-line String Literals

If you need a string that spans several lines, use a multiline string literal—a sequence of characters surrounded by three double quotation marks:

let picardQuotation = """
Someone once told me that time was a predator that stalked us all our lives. 
I rather believe that time is a companion who goes with us on the journey 
and reminds us to cherish every moment, because it will never come again. 

What we leave behind is not as important as how we've lived. 
After all Number One, we're only mortal.
"""

It’s important that the string start on the next line after the opening quotes, and that the closing quotes also are on the line after the end of the string.

Learn to concatenate strings

Concatenation refers to combining two or more strings together to make a new string. To concatenate strings in Swift, you use the + operator.

let string1 = "Live long"
let string2 = "prosper"

let spockGreeting = string1 + " and " + string2
print(spockGreeting) //Live long and prosper

Learn to use string interpolation to include variable values in a string

String interpolation allows you create a string that includes the value of constants or variables. Let's say you have an integer that represents the number of starships Starfleet has. 🚀

You want to print a string that says “Starfleet has ___ starships.”. String interpolation can be used to create this string.

let numberOfShips = 450
let stringToPrint = "Starfleet has \(numberOfShips) starships."
print(stringToPrint) //Startfleet has 450 starships.

In the example above, the value of numberOfShips is inserted into a string literal as \(numberOfShips). This placeholder is replaced with the actual value of numberOfShips when the string interpolation is evaluated to create an actual string.

Learn to use arithmetic operators to add, subtract, multiply, and divide variables

There are four basic arithmetic operators: add (+), subtract (-), multiply (*), and divide (/). You can use them directly on numbers, or on constants or variables.

Addition, subtraction, and multiplication

These operators work the way you’d expect. For example:

let answer = 2 * 14
let score = 1 + 2 + 3

let birthYear = 1901
let currentYear = 2019
let age = currentYear - birthYear

Division

Remember from our previous lesson that Int (and UInt) values can only store whole numbers. When you divide two Intsby each other, the result will also be an Int, and will be the result of the division rounded down to the nearest whole number.

let x = 5
let y = 2
let result = x / y 
print(result) // 2

If you’re doing division and need fractional values, you should use floating point numbers (see previous lesson on type annotations):

let x: Double = 5
let y: Double = 2
let result = x / y
print(result) // 2.5

Learn to use comments to make code easier to understand

You should always strive to write code that is clear and easy for humans to understand. Usually, this should mean that the code itself is nicely written, well-formatted, your variables have carefully chosen names, etc.

However, sometimes, it’s useful to be able to write little comments to explain what a particular part of the code is doing. Comments are notes to you or another future reader of the code, but the compiler ignores them.

There are two ways to create comments in Swift. You can create a comment on the same line as some code by prefixing your comment with two forward slashes ():

let birthYear = 1988
let currentYear = 2019
let age = currentYear - birthYear // Calculate current age
print(age)

Anything after the slashes will be ignored until the next line break.

If you want to write a comment that spans multiple lines, you can put your comments between /*and */:

/* This is a longer comment.
It has multiple lines.
The compiler ignores everything here.
*/

Challenge

Now it's your turn! Go ahead and try the following challenges and post your results below! Don't have macOS to run your Swift code? No worries, head on over to repl.it - an online Swift Editor and IDE!

String Literals: Create a string literal constant introducing yourself. Your introduction should include your name, where you're from, what you like to do for fun, etc.

String Concatenation: Create a constant for your favorite vacation destination. Using string concatenation, print out a string that says "I love to travel to [favorite travel destination]."

String Interpolation: Using the constant you created above, print out the same string: "I love to travel to [favorite travel destination]." using string interpolation

Calorie Goal: Below you have constants for the number of calories you burned each day over the last week. Using simple arithmetic find the average number of calories burned. Add 100 calories to the average and use string interpolation to print out "Your new move goal for the week is [your calculated goal].

let mondayCalories = 340
let tuesdayCalories = 420
let wednedayCalories = 200
let thursdayCalories = 625
let fridayCalories = 500
let saturdayCalories = 1_090
let sundayCalories = 300

Like this post?

You can find more by following me on twitter 😄: @joshuarutkowski

Thanks for reading!

Discussion (0)