SafeNest
为所有Swift开发者提供的“安全巢穴”。该巢穴提供了类似JSON的动态存储,并公开了访问/更新嵌套值的方法。
用法
要使用这个巢穴
import SafeNest
let nest1 = SafeNest.builder().build()
let nest2 = SafeNest.empty()
let nest3 = SafeNest.empty()
.cloneBuilder()
.with(initialObject: ["a" : 1])
.with(pathSeparator: "$") // Now you need to use "a$b$c$d"
.build()
要访问任何节点的值,请使用以下方法
nest.value(at: String);
此函数的参数应是一个字符串,其元素由指定的pathSeparator(默认为“.”)连接。返回值封装在Try实例中,允许映射/flatMapping https://github.com/protoman92/SwiftFP/blob/master/SwiftFP/Try.swift。例如
nest.value(at: "a.b.c.d.e") // Returns type Try<Any>
nest.value(at: "a.b.c.d.e").cast(Int.self) // Returns type Try<Int>
nest.value(at: "a.b.c.d.e").cast(String.self) // Returns type Try<String>
nest.decode<D>(at: "a.b.c.d.e, ofType: D) // Returns type Try<D>, where D: Decodable
要更新某个节点的值,请调用
try nest.update(at: String, value: Any) // This method mutates
try nest.updating(at: String, value: Any) // This method returns a new nest.
try nest.encode(at: String, value: Encodable) // This method encodes an object and deposit at a node.
巢穴将更新该节点的值,并在必要时创建新的字典。
请注意,当前仅支持[String : Any]字典和[Any]数组。考虑到可能从后端服务器接收的有效载荷类型,一般应该没问题。
与Redux一起使用
一个巢穴可以作为一个基于Redux的应用的全球状态容器的如下所示
- 客户端接收到的有效载荷如下
{
"a": { "b": [1, 2, 3, { "c": { "d": "This is so nested" } }] },
"b": { "c": { "0": 1, "1": 2, "2": 3, "3": 4 } }
}
- 然后可以使用以下方法访问嵌套属性
nest.value(at: "a.b.0") // Returns Try.success(1)
nest.value(at: "b.c.1") // Returns Try.success(2)
nest.value(at: "a.b.3.c.d") // Returns Try.success("This is so nested")
nest.value(at: "a.b.3.d.e") // Returns Try.failure("...")
- 然后我们可以使用这些值来驱动状态变化。
更具体的例子,请查看此存储库中包含的演示或访问https://github.com/protoman92/HMReactiveRedux-Swift中的演示。