Swift Cheatsheet
Swift Cheatsheet
Control Flow
If Statements
if condition {
} else if anotherCondition {
} else {
Switch Statements
switch someValue {
case outcome1:
// Respond to outcome1
default:
Loops
For-in loop
/// Use for-in loops to iterate over a sequence
print(fruit)
/// lower...upper
print(variable) // prints 1 to 10
/// lower..<upper
print(variable) // prints 0 to 9
While loop
/// Use while loops to perform a set of code
/// until a condition becomes false
while conditionIsTrue {
doSomething()
}
var count = 0
while count < 2 {
print(count)
count += 1 // Increment count by 1
}
Repeat-While
/// Performs a single pass through the code
/// before considering the loop's condition
repeat {
doSomething()
} while conditionIsTrue
var count = 0
repeat {
print(count)
count += 1 // Increment count by 1
} while count < 2
Operators
Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
1 + 2 // equals 3
2 - 1 // equals 1
1 * 2 // equals 2
Conditional Operators
Operator Description
== Equal to
!= Not equal to
Nil-coalesing Operator
let defaultColor: Color = .red
Range Operators
Operator Description
Declaring Types
Reference Types
Classes
/// Use classes if you want to pass objects by reference
init(storedProperty: Type) {
self.storedProperty = storedProperty
Declaring Types
Reference Types
Classes
/// Use classes if you want to pass objects by reference
init(storedProperty: Type) {
self.storedProperty = storedProperty
Value Types
Structures
/// Use struct if you want to model data or pass objects
/// by value
struct Model {
Enumeration
/// Use enumeration to model a range of values
enum Compass {
Protocols
protocol Printable {
func print()