O'Reilly logo

Swift Quick Syntax Reference by Matthew Campbell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter    2

Declaring Constants and Variables

While you can use values like the string "Hello World" from the previous chapter or a number like 3.14 directly in code, usually you assign values like these to either a variable or a constant. You can give values a convenient name using variables and constants in Swift.

Variables can change their values over time, while constants get an assigned value and keep that value throughout the execution of a program. Both variables and constants can store only one type of data.

Constants

Let’s reproduce the Hello World example from Chapter 1 using a constant. Listing 2-1 shows how to store the string "Hello World" in a constant named s1.

Listing 2-1. Hello World Constant

let s1:String = "Hello World"

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required