Print to console: print("Hello, World!")
Datatypes
Int
: 1, 2, …Float
: 1.1, 1.2 …Double
: 1.1, 1.2 …Bool
: true, falseString
: “a”, “ABC”, …type(of: <value>)
<type>(<value>)
Values are never implicitly convertedVariables and Constants
var <name> [: <type>] = <value>
var someNum = 10
let <name> [: <type>] = <value>
let someNum = 10
_
is “don’t care”Operators
==
!=
Strings
let literalStr = "This is a literal string!"
let initializerStr = String("This is an initialized string!")
""" ... [\] ... """
"Variable interpolated: \(<expression>)"
"Unicode: \u{xxxx}"
<strName>.uppercased()
<strName>.lowercased()
<strName>.count()
Data Structures
let
| var
rules follow!let arr = Array<<type>>()
let arr: [<type>] = []
<arrName>.count
<arrName>.append(<val>)
<arrName>.remove(at: [Int])
let set = Set<<type>>()
let set: Set[<type>] = []
<setName>.count
<setName>.insert(<val>)
let dict = Dictionary<<keyType>, <valType>>()
let dict: [<keyType>: <valType>] = [:]
Note the colon here for empty<dictName>[<key>] [ = <value> ]
let original = <dictName>.updateValue(...)
let tup = (1, 2, 3)
Optionals
var nullableSomething: <type>?
Note the ?
<optionalName>!
Note the !
, use with cautionif <optionalName> != nil { ... }
if let <optionalName> [= <optionalName>] { ... }
<optionalName> ?? <defaultValue>
Looping
for <name> in <Array> { ... }
for (<name>, <idx>) in <Array>.enumerated() { ... }
for (<key>, <value>) in <dictName> { ... }
for <name> in x...y { ... }
for <name> in x..<y { ... }
while <condition> { ... }
repeat { ... } while <condition>
Branching
if <condition> {} else {}
switch <name> { case <expression>: ... <default>: }
No “break” requiredFunctions
Definition:
// Syntax:
// fun <name>([<labelName>] <paramName>: <type>) [-> <type>] { ... }
// Example 1
func printHello() {
print("Hello")
}
// Example 2
func addTwoNumbers(numOne: Int, numTwo: Int) -> Int {
numOne + numTwo
}
// addTwoNumbers(numOne: 1, numTwo: 2)
// Example 3
func addTwoNumbersWithDifferentNames(a numOne: Int, b numTwo: Int) -> Int {
numOne + numTwo
}
// addTwoNumbersWithDifferentNames(a: 1, b: 2)
// NOTE: Labels cannot be used inside function body
// Example 4
func addTwoNumbersWithDefaultParam(_ numOne: Int, b numTwo: Int) -> Int {
numOne + numTwo
}
// addTwoNumbersWithDefaultParam(1, b: 2)
// NOTE: "return" keyword is not required for single line body
{}
){ (<name>) in <retValue> }
is like a lambda of sorts for func x(<name>: <type>) -> <retType> { return <retValue> }
Tips
Int.random(in: x...y)