-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Dictionary+Extensions.swift
50 lines (46 loc) · 1.43 KB
/
Dictionary+Extensions.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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import OrderedCollections
extension Dictionary {
@inlinable
@discardableResult
public mutating func memoize(key: Key, body: () throws -> Value) rethrows -> Value {
if let value = self[key] {
return value
}
let value = try body()
self[key] = value
return value
}
}
extension Dictionary {
public init<S>(throwingUniqueKeysWithValues keysAndValues: S) throws where S: Sequence, S.Element == (Key, Value) {
self.init()
for pair in keysAndValues {
guard !self.keys.contains(pair.0) else {
throw StringError("duplicate key found: '\(pair.0)'")
}
self[pair.0] = pair.1
}
}
}
/*
extension OrderedDictionary {
public subscript(key: Key, `default` `default`: Value) -> Value {
set {
self[key] = newValue
} get {
self[key] ?? `default`
}
}
}
*/