File tree 2 files changed +49
-0
lines changed
2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change @@ -12,3 +12,26 @@ import Foundation
12
12
13
13
/// Typealias for an any typed dictionary for arbitrary usage to store context.
14
14
public typealias Context = [ ObjectIdentifier : Any ]
15
+
16
+ extension Context {
17
+ /// Get the value for the given type.
18
+ public func get< T> ( _ type: T . Type = T . self) -> T {
19
+ guard let value = getOptional ( type) else {
20
+ fatalError ( " no type \( T . self) in context " )
21
+ }
22
+ return value
23
+ }
24
+
25
+ /// Get the value for the given type, if present.
26
+ public func getOptional< T> ( _ type: T . Type = T . self) -> T ? {
27
+ guard let value = self [ ObjectIdentifier ( T . self) ] else {
28
+ return nil
29
+ }
30
+ return value as! T
31
+ }
32
+
33
+ /// Set a context value for a type.
34
+ public mutating func set< T> ( _ value: T ) {
35
+ self [ ObjectIdentifier ( T . self) ] = value
36
+ }
37
+ }
Original file line number Diff line number Diff line change
1
+ // This source file is part of the Swift.org open source project
2
+ //
3
+ // Copyright (c) 2020 Apple Inc. and the Swift project authors
4
+ // Licensed under Apache License v2.0 with Runtime Library Exception
5
+ //
6
+ // See http://swift.org/LICENSE.txt for license information
7
+ // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
8
+
9
+ import XCTest
10
+
11
+ import TSCUtility
12
+
13
+ struct SomeType {
14
+ var name : String
15
+ }
16
+
17
+ class ContextTests : XCTestCase {
18
+ func testBasics( ) {
19
+ var ctx = Context ( )
20
+ ctx. set ( SomeType ( name: " test " ) )
21
+ XCTAssertEqual ( ctx. get ( SomeType . self) . name, " test " )
22
+
23
+ ctx. set ( SomeType ( name: " optional " ) )
24
+ XCTAssertEqual ( ctx. getOptional ( SomeType . self) ? . name, " optional " )
25
+ }
26
+ }
You can’t perform that action at this time.
0 commit comments