forked from facebook/componentkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TreeNodeValueStore.swift
53 lines (44 loc) · 1.44 KB
/
TreeNodeValueStore.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
/*
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
import Foundation
import ComponentKit
final class TreeNodeValueStore<Value> {
private let valueProvider: () -> Value
private var link: (node: CKTreeNode, index: Int, value: Value)?
init(valueProvider: @escaping () -> Value) {
self.valueProvider = valueProvider
}
@discardableResult
func link(with node: CKTreeNode, at index: Int) -> Bool {
let wasFirstInit = CKSwiftInitializeState(node, index, valueProvider)
let untypedValue = CKSwiftFetchState(node, index)
guard let value = untypedValue as? Value else {
preconditionFailure("Unexpected value \(String(describing: untypedValue))")
}
link = (node, index, value)
return wasFirstInit
}
func get() -> Value {
guard let link = link else {
preconditionFailure("Attempting to read state before scope handle location linked.")
}
return link.value
}
func set(_ value: Value) {
guard let nonNilLink = link else {
preconditionFailure("Attempting to write state before `-body`.")
}
link!.value = value
CKSwiftUpdateState(nonNilLink.node, nonNilLink.index, value)
}
var isLinked: Bool {
link != nil
}
}