Swift Cheatsheet

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 array
  • s[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 check
  • String(string.sorted()) // alphabetized string

Array / Stack / Queue

  • var array = [Int]()
  • var array = Array(repeating: 0, count: n) //array of size n
  • array.append(item) // add to end
  • array.firstIndex(of: item) // index (Swift5)
  • array.remove(at: index)
  • array.compactMap { $0 } // remove nils
  • array.reduce([], +) // combine arrays

Set

  • var set = Set() // needs to be var to allow insert
  • Set(array) // cast array to set
  • set.insert(item)
  • let itemOptional = set.remove(item)
  • set.contains(item)

Dictionary / Map (HashMap)

  • var map = [String: String]()
  • map["foo"] = "bar" // insert and overwrite
  • let optionalValue = map["foo"] // get (nil if doesn't exist)
  • map["foo"] == nil // check if key exists
  • map["foo"] = nil // removes a key
  • map.forEach { print($0.value) } // prints each value stored

Loops

  • for item in array
  • while 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^y
  • abs(num) // absolute value

Data / File

  • let file = Bundle.main.path(forResource: "filename", ofType: "ext") // load filename.ext from project
  • let data = try? String(contentsOfFile: file) // extract data from file
  • let classInstance = JSONDecoder().decode(ClassName.self, from: data) // json data into class
  • let string = String(data: data, encoding: .utf8) // data into string
  • let data = string.data(using: .utf8) // string into data

Leave a Reply

Your email address will not be published. Required fields are marked *