Skip to content

Instantly share code, notes, and snippets.

@RinniSwift
Last active May 31, 2019 19:27
Show Gist options
  • Save RinniSwift/744373f9f346c0bbb69ecf8255bcb065 to your computer and use it in GitHub Desktop.
Save RinniSwift/744373f9f346c0bbb69ecf8255bcb065 to your computer and use it in GitHub Desktop.
// 1. initializing dictionaries with the minimumCapacity(_:)
var someDict = Dictionary<String, Int>(minimumCapacity: 8)
someDict.capacity // 12
// 2. initializing dictionaries with unique key-value sequences
let newDict = Dictionary(uniqueKeysWithValues: zip(["one", "two", "three"], 1...3))
// ["two": 2, "three": 3, "one": 1]
// 3. initializing dictionaries with sequence of key-value tuples (drops duplicates)
let romanNumTuples = [("I", 1), ("V", 5), ("X", 10), ("L", 50), ("L", 44)]
var newRomanNums = Dictionary(romanNumTuples, uniquingKeysWith: {(first, _) in first}) // drops duplicates after it's first found key.
var newRomanNums1 = Dictionary(romanNumTuples, uniquingKeysWith: {(_, last) in last}) // drops duplicates before it's last found key.
// newRomanNums = ["X": 10, "I": 1, "V": 5, "L": 50]
// newRomanNums1 = ["L": 44, "V": 5, "X": 10, "I": 1]
// 4. intializing dictionaries with grouping values for repeated keys
let weekDays = ["Monday", "Tuesday", "Wednesday" ,"Thursday" ,"Friday"]
var weekDaysByLetter = Dictionary(grouping: weekDays, by: { $0.first! })
// ["M": ["Monday"], "W": ["Wednesday"], "T": ["Tuesday", "Thursday"], "F": ["Friday"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment