A list of helpful methods and syntax to reference before coding challenges and whiteboard interviews.
Download: SwiftCheatsheet.playground
Last update on 2020-09-22 for Swift 5.1
String
string.map { $0 } // Convert String to Character arrays[s.index(s.startIndex, offsetBy: i)] // Character at "i"s[s.index(s.startIndex, offsetBy: i)..<s.index(s.startIndex, offsetBy: i + length)] // substring of length at "i"string.contains(char) // Bool checkString(string.sorted()) // alphabetized string
Array / Stack / Queue
var array = [Int]()var array = Array(repeating: 0, count: n) //array of size narray.append(item) // add to endarray.firstIndex(of: item) // index (Swift5)array.remove(at: index)array.compactMap { $0 } // remove nilsarray.reduce([], +) // combine arrays
Set
var set = Set() // needs to be var to allow insertSet(array) // cast array to setset.insert(item)let itemOptional = set.remove(item)set.contains(item)
Dictionary / Map (HashMap)
var map = [String: String]()map["foo"] = "bar" // insert and overwritelet optionalValue = map["foo"] // get (nil if doesn't exist)map["foo"] == nil // check if key existsmap["foo"] = nil // removes a keymap.forEach { print($0.value) } // prints each value stored
Loops
for item in arraywhile condition {}repeat {} while condition
Enums
guard case let .enumType(property) = enumInstance else { return }
// let property = enumInstance(property)if case .enumType = enumInstance { ... }if case 1...100 = num { ... } // if 1 <= num && num <= 100
Math
min(a, b)max(a, b)NSDecimalNumber(decimal: pow(x, y)).intValue //x^yabs(num) // absolute value
Data / File
letfile = Bundle.main.path(forResource: "filename", ofType: "ext") // load filename.ext from projectletdata =try? String(contentsOfFile: file) // extract data from fileletclassInstance = JSONDecoder().decode(ClassName.self, from: data) // json data into classletstring = String(data: data, encoding: .utf8) // data into stringletdata = string.data(using: .utf8) // string into data