Data Types

Swift is a strongly-typed language.

Basic Data Types:

Swift provides a rather large number of types. However, you can write perfectly good programs using only four of the Basic Swift Data Types.

Here are some examples of declaring and initializing variables:

var age: Int = 28
var price: Double = 8.99
var message: String = "Game Over"
var lateToWork: Bool = true

Naming Constants and Variables:

Constant and variable names can contain almost any character, including Unicode characters:

let π = 3.14159
let 你好 = "你好世界"
let 🙂 = "happy"

Constant and variable names can’t contain whitespace characters, mathematical symbols, arrows, private-use Unicode scalar values, or line- and box-drawing characters. Nor can they begin with a number, although numbers may be included elsewhere within the name.

Numeric Type Conversion:

A type cast is basically a conversion from one type to another.

The notation (Type)value means “convert value to Type“. So for example:

double weight1;
int weight2;
weight1 = 154.49;
weight2 = (int) weight1;
// weight2 is now 154

Note: Going from a double to an int simply removes the decimal. There’s no rounding involved.

Author

Codecademy Team

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

Meet the full team