import Foundation
// Expand Tilde
let path: String = NSString(string: "~").expandingTildeInPath
// Current user home
let homeURL: URL = FileManager.default.homeDirectoryForCurrentUser
let homeURL: String = NSHomeDirectory()
// Current user documents
let documentsURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
// Append to URL
let fooURL = documentsURL.appendingPathComponent("foo.html")
// Check if file exists (return true/false)
let fileExists = FileManager().fileExists(atPath: fooURL.path)
// Enumerate files at a path
let path: String = "/Users/nathanr/Desktop/"
let files = FileManager().enumerator(atPath: path)
while let file = files?.nextObject() {
print(file)
}
import foundation
// Access by index
let coordinates = (2, 3)
let x = coordinates.0
let y = coordinates.1
// Inferred to be of type (x: Int, y: Int)
let coordinatesNamed = (x: 2, y: 3)
let x = coordinatesNamed.x
let y = coordinatesNamed.y
// Shorthand assignment
let coordinates3D = (x: 2, y: 3, z: 1)
let (x, y, z) = coordinates3D
let (x, y, _) = coordinates3D // To ignore an element (z)
import foundation
// If you wanted to determine the minimum and maximum of two variables, you could use if statements, like so:
let a = 5
let b = 10
let min: Int
if a < b {
min = a
} else {
min = b
}
let max: Int
if a > b {
max = a
} else {
max = b
}
//The ternary conditional operator takes a condition and returns one of two values, depending on whether the condition was true or false. The syntax is as follows:
// (<CONDITION>) ? <TRUE VALUE> : <FALSE VALUE>
// You can use this operator to rewrite your long code block above, like so:
let a = 5
let b = 10
let min = a < b ? a : b
let max = a > b ? a : b
// This code block makes use of labeled statements, labeling the two loops as rowLoop and the columnLoop, respectively. When the row equals the column inside the inner columnLoop, the outer rowLoop will continue. You can use labeled statements like these with break to break out of a certain loop. Normally, break and continue work on the innermost loop, so you need to use labeled statements if you want to manipulate an outer loop.
var sum = 0
rowLoop: for row in 0..<8 {
columnLoop: for column in 0..<8 {
if row == column {
continue rowLoop
}
sum += row * column
}
}