Skip to content

Instantly share code, notes, and snippets.

View RinniSwift's full-sized avatar
🔸
Swifting

Rinni Swift RinniSwift

🔸
Swifting
View GitHub Profile
// 1. empty dictionary initialization
var numbers = Dictionary<String, Int>()
var newNumbers: Dictionary<String, Int> = Dictionary()
// 2. empty dictionary initialization using dictionary literals
var nums = [String: Int]()
var newNums: [String: Int] = [:]
// 3. predefininig elements with dictionary literals
var romanNumerals = ["I": 1, "V": 5, "X": 10, "L": 50] // using type inference
// 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 dict = ["blue": 2, "grey": 1, "purple": 4, "red": 2]
// subscript(key:)
dict["blue"] // Optional(2)
// subscript(key:default:)
dict["grey", default: 0] // 1
// subscript(position:)
if let ind = dict.firstIndex(where: { ($0.key == "red") }) {
var dict = ["blue": 2, "grey": 1, "red": 2]
// for-each loop
dict.forEach { pair in
print(pair)
}
// for-in loop
for pair in dict {
print(pair)
var dict = ["blue": 2, "grey": 1, "red": 2]
var newDict = ["pink": 3, "red": 5]
dict.merge(newDict) { (current, _) in current } // ["blue": 2, "grey": 1, "red": 2, "pink": 3]
dict.merge(newDict) { (_, new) in new } // ["blue": 2, "grey": 1, "red": 5, "pink": 3]
let mergedDict = dict.merging(newDict) { (current, _) in current} // ["blue": 2, "grey": 1, "red": 5, "pink": 3]
protocol Payload {
associatedtype Key
associatedtype Value
var key: Key { get set }
var value: Value { get set }
}
struct CachePayload<T: Hashable, U>: Payload {
var key: T
var value: U
init(key: Key, value: Value) {
self.key = key
self.value = value
}
}
/// A Node class to represent data objects in the LinkedList class
class Node<T: Payload> {
var payload: T
var previous: Node<T>?
var next: Node<T>?
init(value: T) {
self.payload = value
}
class LRUCache<T: Hashable, U> {
/// Total capacity of the LRU cache.
private(set) var capacity: UInt
/// LinkedList will store elements that are most accessed at the head and least accessed at the tail.
private(set) var linkedList = DoublyLinkedList<CachePayload<T, U>>()
/// Dictionary that will store the element, U, at the specified key.
private(set) var dictionary = [T: Node<CachePayload<T, U>>]()
/// LRUCache requires a capacity which must be greater than 0
class LRUCache<T: Hashable, U> {
// ...
/// Sets the specified value at the specified key in the cache.
func setObject(for key: T, value: U) {
let element = CachePayload(key: key, value: value)
let node = Node(value: element)
if let existingNode = dictionary[key] {