println("Hello World")
print("Hello")
let myConst = 42
, var myVar = 50
let implicitD = 70.0
, let explicitD: Double = 70
var
)var dict = ["A": "value1", "B": "value2"]
Control FLow
for score in myArray {
if score > 50 {
// asdf
} else {
// something else
}
}
nil
. Write a question mark after the type to mark as optionalvar optionalString: String? = "Hello"
for (key, val) in myDict {}
for i in 1..5
Swift is a type-safe language. Encourages you to be clear about hte type of values your code can work with.
0b
prefix), octal (0o
), hexadecimal (0x
), all stored the same, as Ints1.25e2
is 125.0
Int
by default unless optimizing performance or memory usageUInt8
, Int8
are available, among othersUInt16(some_other_num)
typealias AudioSample = UInt16
can be used for more context in code.
Bool
s can only be true
or false
. Type safety prevents non-Boolean values from being used for conditionals.
Tuples group multiple values into a single compound value. Tuples types can be any permutation of any number of different types:
let http404Error = (404, "Not Found")
// http404Error is of type (Int, String), and equals (404, "Not Found")
// now decompose the tuple into two constants
let (statusCode, statusMessage) = http404Error
Use optionals in situations where a value may be absent. It says there is a value, and it equals x, or there isn't a value at all.
let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
// then convertedNumber is inferred to be an `Int?` type
nil
Used to find out whether an optional contains a value, and if so, make it available as a temp const/var:
if let actualNumber = Int(possibleNumber) {
print("\"\(possibleNumber)\" has an integer value of \(actualNumber)")
} else { // ...
If after some logic, an optional may be guaranteed to have a value. At this point, it is useful to remove the need to check and unwrap the optional's value every time.
String!
. Gives the permission to unwrap optionals automaticallyOptionals communicate success through having a value, or nil
. Functions communicate through erros.
func canThrowAnError() throws {}
try
before calling a function, followed by catch
catch Error.MyTypeOfError {}
for specific casesvar
s"\(muliplier) times 2.5 is \(Double(multiplier)*2.5)"
Arrays, Sets, Dictionaries. Collections are mutable; able to add, remove, change items in a collection.
Array<Element>
can be shortened as [Element]
.[Element]()
.enumerate()
method iterates over an array, returning a tuple composed of the (index, value)
Set<String>
Dictionary<Key, Value>
can be shorthanded as [Key: Value]
var namesOfInts = [String: Int]()
func sayHello(personName: String) -> String {}
(return val is optional, can return tuples). Example:
let bounds = minMax([8, -6, 2, 109, 3, 71])
print("min is \(bounds.min) and max is \(bounds.max)")
// Prints "min is -6 and max is 109"
func sayHello(to person: String, and anotherPerson: String) -> String {
return "Hello (person) and (anotherPerson)!"
}
print(sayHello(to: "Bill", and: "Ted"))
- you can assign default parameter values: `func someFunction(parameterWithDefault: Int = 12)` - a function can take an arbitrary number of parameters: `func arithmeticMean(numbers: Double...) -> Double {`, where `numbers` is a list of doubles - every function has a *function type*, like `(Int, Int) -> Int` - `var mathFunc: (Int, Int) -> Int = addTwoInts`; then call `mathFunc(2, 3)` >>> `5` - you can pass functions as parameters - functions can be return types:
swift
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
return backwards ? stepBackward : stepForward
}
```
a self contained block of functionality that can be passed around in your code.
closure expressions are unnamed closures that can capture values from their surrounding context
reversed = names.sort({ (s1: String, s2: String) -> Bool in
return s1 > s2
})
A closure captures values around it. It can be referenced outside of the original scope to modify those values, even if the scope doesn't exist anymore.
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
func incrementer() -> Int {
runningTotal += amount
return runningTotal
}
return incrementer
}
a closure that is automatically created to wrap an expression being passes as an argument.
An enumerator defines a common type for a group of related values, and gives type safety.
assigns a related name to a set of integer values
enum CompassPoint {
case North
case South
case East
case West
}
defines CompassPoint.West
, then use switch statements with case .North:
as conditionals
Flexible constructs that are the building blocks for code. Swift does not require you to create separate interface