6
6
// Copyright © 2016 Heavy. All rights reserved.
7
7
//
8
8
9
+ /// Used for storing different behavior types so they can be retrieved easily.
10
+ /// - Todo: Add pooling
9
11
public struct BehaviorStore {
10
12
typealias BehaviorID = Int
11
13
typealias Behaviors = [ Behavior ]
@@ -16,32 +18,34 @@ public struct BehaviorStore {
16
18
public init ( ) { }
17
19
18
20
private func has( type: Behavior . Type ) -> BehaviorID ? {
19
- guard let id = hasID ( type) where hasStored ( id ) else { return nil }
21
+ guard let id = hasIndex ( type) where storage [ id ] != nil else { return nil }
20
22
return id
21
23
}
22
24
23
- private func hasID ( type: Behavior . Type ) -> BehaviorID ? {
25
+ private func hasIndex ( type: Behavior . Type ) -> BehaviorID ? {
24
26
guard let id = storageIDs. indexOf ( { $0 == type} ) else { return nil }
25
27
return id
26
28
}
27
29
28
- private func hasStored ( id : BehaviorID ) -> Bool {
29
- guard let results = storage [ id ] else { return false }
30
- return !results . isEmpty
31
- }
32
-
30
+ /// Find all of the `Behavior.Type` this particular store contains.
31
+ ///
32
+ /// - parameter type: The `Behavior.Type` you wish to find.
33
+ ///
34
+ /// - returns: A collection of the `Behavior.Type` you are looking for or `nil`.
33
35
public func find< T: Behavior > ( type: T . Type ) -> [ T ] ? {
34
- guard let id = has ( type) ,
35
- let store = storage [ id]
36
- else { return nil }
36
+ guard let id = has ( type) ,
37
+ store = storage [ id] else { return nil }
37
38
return store. flatMap { $0 as? T }
38
39
}
39
40
41
+ /// Add a reference to a given `Behavior` to the store.
42
+ ///
43
+ /// - parameter behavior: The `Behavior` reference you wish to store.
40
44
public mutating func add< T: Behavior > ( behavior: T ) {
41
45
let type = behavior. dynamicType
42
- let doesHaveID = hasID ( type)
43
- let id = doesHaveID ?? storageIDs. count
44
- if doesHaveID == nil {
46
+ let index = hasIndex ( type)
47
+ let id = index ?? storageIDs. count
48
+ if index == nil {
45
49
storageIDs. append ( type)
46
50
}
47
51
if storage [ id] == nil {
@@ -50,6 +54,9 @@ public struct BehaviorStore {
50
54
storage [ id] ? . append ( behavior)
51
55
}
52
56
57
+ /// Remove this `Behavior` from the store.
58
+ ///
59
+ /// - parameter behavior: A reference to the behavior you wish to remove.
53
60
public mutating func remove( behavior: Behavior ) {
54
61
guard let id = has ( behavior. dynamicType)
55
62
where storage [ id] ? . count > 0
0 commit comments