-
Literals
Swift supports the following literals: "integer literals", "floating-point literals", "string literals", and "Boolean literals".
Here are some examples:
- Integer literals: 1
(decimal), 0b1
(0b: binary), 0o1
(0o: octal), 0x1
(0x: hexadecimal)
- Floating-point literals: 1.0
, 1.0e2
, 0x1.0p2
(0x: hexadecimal)
- String literals: "swift string"
- Boolean literals: true
, false
It's possible (to improve numbers readability) by using underscore "_" characters to separate the digits of a number (integer & floating-point literals):
1_000
1_000.0
It's also possible to begin numbers (integer & floating-point literals) with leading zeros:
001
001.0
You can include an expression in a string by using the following syntax "\(expression)".
let c3 = "The current date and time: \(NSDate())"
-
Constants & Variables
Use the keyword let
to declare constants.
Use the keyword var
to declare variables.
The compiler can decide the type of the constant/variable by inferring the type from the value assigned to the constant/variable:
let c1 = 10
(the compiler infers that the constant is an integer because the assigned value is an integer)
var v1 = 5.0
(the compiler infers that the variable is a double because the assigned value is a double)
Type annotation: you can explicitly specify the type of a constant/variable by writing the type after the constant/variable name separated by a colon.
let c2: Int = 10
var v2: Double = 5.0
You don't have to specify a value for the constant when you declare it.
But you won't be able to use the constant if it is not initialized.
Also, when you declare a constant without giving it a value, you have to specify its type.
let c21: Int; // OK!
let c22; // compiler error: type annotation missing in pattern
let c23 = c21; // compiler error: Constant 'c21' used before being initialized
You cannot assign a value of a specific type to a variable with a different type.
You have to use the explicit conversion to convert from one type to another:
You need to create a new instance of a type by calling a specific initializer.
var v3: String = 10; // compiler error: Cannot convert value of type 'Int' to specified type 'String'
var v4: String = String(10); // OK!
let c3: Int = 3.5; // compiler error: Cannot convert value of type 'Double' to specified type 'Int'
let c4: Int = Int(3.5); // OK!
-
Optional Type (Optional<T>)
An Optional
type allows a variable to hold a value
or nil
.
The Optional
type is an enumeration with two values: None
and Some(TYPE)
Use a question mark (?) after the type of a variable to mark the value of the variable as optional:
var var1OptionalInt: Int? = 5
(short syntax)
var var2OptionalInt: Optional<Int> = 5
(explicit syntax)
If you don't specify a value for an optional, its value is set by default to nil
.
You can assign an optional to another optional:
var var1Int: Int? = var1OptionalInt
var var2Int = var1OptionalInt // the type of the variable 'var2Int' is inferred by the compiler as Optional<Int>
Use an exclamation mark (! operator
) after the name of an optional to access its value:
var var3Int: Int = var1OptionalInt!
You will get a compiler error if you don't use the ! operator
to access the value of an optional.
var var4Int: Int = var1OptionalInt; // compiler error: Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?
You will get a runtime error if you use the ! operator
but the value of the optional is nil
.
-
Implicitly Unwrapped Optional Type (ImplicitlyUnwrappedOptional<T>)
An Implicitly Unwrapped Optional
type allows a variable to hold a value or nil.
Use an exclamation mark (!) after the type of a variable to mark the value of the variable as implicitly unwrapped optional:
var var1ImplicitlyUnwrappedOptionalInt: Int! = 5
(short syntax)
var var2ImplicitlyUnwrappedOptionalInt: ImplicitlyUnwrappedOptional<Int> = 5
(explicit syntax)
If you don't specify a value for an optional, its value is set by default to nil
.
You can access directly to the value of an implicitly unwrapped optional:
var var1Int: Int = var1ImplicitlyUnwrappedOptionalInt
You will get a runtime error if the value of the implicitly unwrapped optional is nil
.
-
Arrays (Array<T> | [T])
Use brackets ([]) to create arrays:
var array1 = ["Hello", "world"]
Use indexes to access elements of an array (index starts from 0, it references the first element of the array):
let array1Elt1 = array1[0]
let array1Elt2 = array1[1]
You can set an explicit array type for a variable:
var array2: [String] = ["Hello", "world"]
(short syntax)
var array3: Array<String> = ["Hello", "world"]
(explicit syntax)
To create an empty array:
var emptyArray1 = [String]()
You can empty an array using a shortcut syntax (the type will be inferred by the compiler):
array1 = []
-
Dictionaries (Dictionary<T, R> | [T:R])
Use brackets ([]) to create dictionaries:
var dictionary1 = ["key1": "Hello", "key2": "world"]
Use keys to access elements of a dictionary:
let dictionary1Elt1 = dictionary1["key1"]
let dictionary1Elt2 = dictionary1["key2"]
You can set an explicit dictionary type for a variable:
var dictionary2: [String:String] = ["key1": "Hello", "key2": "world"]
(short syntax)
var dictionary3: Dictionary<String, String> = ["key1": "Hello", "key2": "world"]
(explicit syntax)
To create an empty dictionary:
let emptyDictionary1 = [String: Int]()
You can empty a dictionary using a shortcut syntax (the type will be inferred by the compiler):
dictionary1 = [:]
-
Tuples
A tuple type is an ordered list of (comma-separated) types placed in parentheses.
To create a tuple:
var tuple1: (Int, Int) = (3,6)
Use the tuple element index to access its value:
You can name the elements of a tuple:
var tuple2: (min:Int, max:Int) = (3,6)
Use the element name (or its index) to access its value:
-
Conditional statements: if ... else if ... else
Use if
to make conditional statements:
if (condition) { body }
if condition { body }
Notes:
► The condition must be a Boolean expression that must be evaluated to true or false.
► Parentheses are optional but braces are required.
You can use if
with let
to initialize a local constant with an optional value.
If the value of the variable is nil
then the conditional evaluate to false.
-
Conditional statements: switch
Use switch
to make conditional statements.
- You don't need to use break
to exit from a case
statement.
- You can use case
with let
to initialize a local constant with the value evaluated by switch
statement.
- You can use where
to add a conditional for the case
statement.
- You must have a default clause or a last case
statement that the compiler can figure out that it will always evaluate to true,
otherwise you will get a compiler error.
To solve this, you can either add a default clause or add a last special case that will always match the the switch value if the first cases didn't:
-
Iteration statements: for
A regular for
statement looks like:
-
Iteration statements: for ... in
You can use for ... in
to iterate over a range of values, an array, or a dictionary:
Range of values:
Use ...
instead of ..<
to include both sides of the range
Array:
Dictionary:
-
Iteration statements: while
A regular while
statement looks like:
You can also use do ... while
statement:
-
Functions
Use the keyword func
to declare functions:
func FUNC_NAME (COMMA_SEPARATED_PARAMS) -> RETURN_TYPE { ... }
Call a function by using its name followed by its arguments:
FUNC_NAME (COMMA_SEPARATED_ARGS)
A simple Example:
You can define default values for the function parameters:
func FUNC_NAME (COMMA_SEPARATED_PARAMS, COMMA_SEPARATED_PARAMS_WITH_DEFAULT_VALUES) -> RETURN_TYPE { ... }
When calling the function, you can skip the arguments for the parameters which have default values.
But if you specify a value for theses arguments, you need to prefix the values with the names of the corresponding parameters.
A simple Example:
You can declare a function that accept an indefinite number of parameters (grouped in an array).
The number is known by the arguments of the function when it's called.
func FUNC_NAME (COMMA_SEPARATED_PARAMS, ARRAY_PARAM_NAME:ARRAY_PARAM_TYPE...) -> RETURN_TYPE { ... }
A simple Example:
-
Nested functions
A function can be declared within another function:
-
Return a function
A function can return another function as its value:
func FUNC_NAME (COMMA_SEPARATED_PARAMS) -> (PARAM_TYPE -> RETURN_TYPE) { ... }
A simple Example:
-
Using a function as an argument
A function can take another function as an argument:
func FUNC_NAME (ANOTHER_FUNC_NAME: PARAM_TYPE -> RETURN_TYPE ) -> RETURN_TYPE { ... }
A simple Example: