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"

Get Swift Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.