Tutorial by Examples

Optionals are a generic enum type that acts as a wrapper. This wrapper allows a variable to have one of two states: the value of the user-defined type or nil, which represents the absence of a value. This ability is particularly important in Swift because one of the stated design objectives of the ...
In order to access the value of an Optional, it needs to be unwrapped. You can conditionally unwrap an Optional using optional binding and force unwrap an Optional using the ! operator. Conditionally unwrapping effectively asks "Does this variable have a value?" while force unwrapping sa...
You can use the nil coalescing operator to unwrap a value if it is non-nil, otherwise provide a different value: func fallbackIfNil(str: String?) -> String { return str ?? "Fallback String" } print(fallbackIfNil("Hi")) // Prints "Hi" print(fallbackIfNil(nil)...
You can use Optional Chaining in order to call a method, access a property or subscript an optional. This is done by placing a ? between the given optional variable and the given member (method, property or subscript). struct Foo { func doSomething() { print("Hello World!") ...
Often when programming it is necessary to make some distinction between a variable that has a value and one that does not. For reference types, such as C Pointers, a special value such as null can be used to indicate that the variable has no value. For intrinsic types, such as an integer, it is mo...

Page 1 of 1