Swift Cheat Sheet
Swift Cheat Sheet
Table of Contents
Introduction 0
Basics 1
Arrays 2
Dictionaries 3
Control Flow 4
Functions 5
Closures 6
Classes 7
Enums 8
Other 9
Protocols 9.1
Extensions 9.2
Operator Overloading 9.3
Generics 9.4
Emoji/Unicode support 9.5
GoodBye 10
2
Swift Cheat Sheet
Introduction 3
Swift Cheat Sheet
Basics
println("Hello, world")
var myVariable = 42 // variable (can't be nil)
let π = 3.1415926 // constant
let (x, y) = (10, 20) // x = 10, y = 20
let explicitDouble: Double = 1_000.000_1 // 1,000.0001
let label = "some text " + String(myVariable) // Casting
let piText = "Pi = \(π)" // String interpolation
var optionalString: String? = "optional" // Can be nil
optionalString = nil
Basics 4
Swift Cheat Sheet
Arrays
// Array
var shoppingList = ["catfish", "water", "lemons"]
shoppingList[1] = "bottle of water" // update
shoppingList.count // size of array (3)
shoppingList.append("eggs")
shoppingList += ["Milk"]
// Array slicing
var fibList = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 5]
fibList[4..<6] // [3, 5]. Note: the end range value is exclusive
fibList[0..<(fibList.endIndex-1)] // all except last item
// Subscripting returns the Slice type, instead of the Array type.
// You may need to cast it to Array in order to satisfy the type checker
Array(fibList[0..<4])
Arrays 5
Swift Cheat Sheet
Dictionaries
// Dictionary
var occupations = [
"Malcolm": "Captain",
"kaylee": "Mechanic"
]
occupations["Jayne"] = "Public Relations"
var emptyDictionary = Dictionary<String, Float>()
Dictionaries 6
Swift Cheat Sheet
Control Flow
// for loop (ignoring the current value of the range on each iteration of th
for _ in 1...3 {
// Do something three times.
}
// while loop
var i = 1
while i < 1000 {
i *= 2
Control Flow 7
Swift Cheat Sheet
// do-while loop
do {
println("hello")
} while 1 == 2
// Switch
let vegetable = "red pepper"
switch vegetable {
case "celery":
let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
let vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy \(x)?"
default: // required (in order to cover all possible input)
let vegetableComment = "Everything tastes good in soup."
}
Control Flow 8
Swift Cheat Sheet
Functions
Functions are a first-class type, meaning they can be nested in functions and can
be passed around
Functions 9
Swift Cheat Sheet
Functions 10
Swift Cheat Sheet
Closures
Functions are special case closures ({})
// Closure example.
// `->` separates the arguments and return type
// `in` separates the closure header from the closure body
var numbers = [1, 2, 3, 4, 5]
numbers.map({
(number: Int) -> Int in
let result = 3 * number
return result
})
// When a closure is the last argument, you can place it after the )
// When a closure is the only argument, you can omit the () entirely
// You can also refer to closure arguments by position ($0, $1, ...) rather
numbers = [2, 5, 1]
numbers.map { 3 * $0 } // [6, 15, 3]
Closures 11
Swift Cheat Sheet
Classes
All methods and properties of a class are public. If you just need to store data in a
structured object, you should use a struct
init(sideLength: Int) {
self.sideLength = sideLength
super.init()
}
func shrink() {
if sideLength > 0 {
--sideLength
}
Classes 12
Swift Cheat Sheet
// If you don't need a custom getter and setter, but still want to run code
// before an after getting or setting a property, you can use `willSet` and
Classes 13
Swift Cheat Sheet
Enums
Enums can optionally be of a specific type or on their own. They can contain
methods like classes.
enum Suit {
case Spades, Hearts, Diamonds, Clubs
func getIcon() -> String {
switch self {
case .Spades: return "♤"
case .Hearts: return "♡"
case .Diamonds: return "♢"
case .Clubs: return "♧"
}
}
}
Enums 14
Swift Cheat Sheet
Protocols
A protocol defines a blueprint of methods, properties, and other requirements that
suit a particular task or piece of functionality.
protocol SomeProtocol {
// protocol definition goes here
}
Protocols 15
Swift Cheat Sheet
Extensions
Add extra functionality to an already created type
Extensions 16
Swift Cheat Sheet
Operator Overloading
You can overwrite existing operators or define new operators for existing or
custom types.
struct Vector2D {
var x = 0.0, y = 0.0
}
@infix func + (left: Vector2D, right: Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y + right.y)
}
Operator Overloading 17
Swift Cheat Sheet
Generics
Generic code enables you to write flexible, reusable functions and types that can
work with any type.
We can use certain type constraints on the types with generic functions and
generic types. Use where after the type name to specify a list of requirements.
Generics 18
Swift Cheat Sheet
// Generic function, which checks that the sequence contains a specified val
func containsValue<
T where T: Sequence, T.GeneratorType.Element: Equatable>
(sequence: T, valueToFind: T.GeneratorType.Element) -> Bool {
return false
}
In the simple cases, you can omit where and simply write the protocol or class
name after a colon. Writing <T: Sequence> is the same as writing <T where
T: Sequence> .
Generics 19
Swift Cheat Sheet
Emoji/Unicode support
You can use any unicode character (including emoji) as variable names or in
Strings.
var = "Smiley"
println( ) // will print "Smiley"
let = " "
var : String[] = []
for in {
.append(+)
}
println() // will print [, , , ]
Emoji/Unicode support 20
Swift Cheat Sheet
GoodBye
Links
Homepage
Guide
Book
Contributing
Feel free to send a PR or mention an idea, improvement or issue!
GoodBye 21