-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinearMap.swift
61 lines (51 loc) · 919 Bytes
/
LinearMap.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
struct LinearMap<K: Hashable, V> : CustomStringConvertible {
var keys = [K](),
vals = [V](),
count = 0
private func findKeyIndex(_ key: K) -> Int? {
for i in 0 ..< count {
if keys[i] == key {
return i
}
}
return nil
}
func get(_ key: K) -> V? {
if let i = findKeyIndex(key) {
return vals[i]
} else {
return nil
}
}
mutating func set(_ key: K, _ val: V) {
if let i = findKeyIndex(key) {
vals[i] = val
} else {
keys.append(key)
vals.append(val)
count += 1
}
}
mutating func remove(_ key: K) {
if let i = findKeyIndex(key) {
keys.remove(at: i)
vals.remove(at: i)
count -= 1
}
}
subscript(key: K) -> V? {
get {
return self.get(key)
}
set(val) {
self.set(key, val!)
}
}
var description: String {
var desc = "LinearMap[\n"
for i in 0 ..< count {
desc += " \(keys[i]) : \(vals[i])\n"
}
return desc + "]"
}
}