尝试 TryCodable 0.1.0

TryCodable 0.1.0

Preston Spalding维护。



  • Preston Spalding

TryCodable

一个围绕 Codable 的小型包装器,使用户在解码和编码值时更加灵活。

入门指南

// TODO: 添加安装 TryCodable 的各种方式。

如何使用

让我们看看使用 Codable 解码 Struct 的基本实现。

struct Person: Decodable {
    let name: String
    let age: Int
    
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        name = try container.decode(String.self, forKey: .name)
        let ageAString = try container.decode(String.self, forKey: .age)
        age = Int(ageAString)!
    }
    
    enum CodingKeys: CodingKey {
        case name
        case age
    }
}

如上面代码所示,我们需要通过 forKey 来指定解码的目标。另外,因为年龄是从我们的服务器传来的字符串,在将其转换为所需的 Int 值之前,我们需要将年龄解码到一个临时变量中。

现在让我们看看使用 TryCodable,这段代码看起来会是什么样子。

struct Person: Decodable {
    let name: String
    let age: Int
    
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        name = try container.decode(.name).valueOrThrow()
        age = try container.decode(.age, map: { Int($0) }).valueOrThrow()
    }
    
    enum CodingKeys: CodingKey {
        case name
        case age
    }
}

我们看到的第一件事是,我们正在从返回类型中推断类型。因此,我们可以移除对 Type.self 的需要。在年龄示例中,我们不需要这个临时变量,我们可以直接对值进行映射和内联转换。

您已经注意到了 valueOrThrow 函数。当我们调用 try container.decode(.name) 时,返回一个包含 successful 情况或 error 情况的枚举。但是您根本不需要对这个情况进行分支,因为已经提供了完成所需所有功能的函数。

这里的三个主要函数是

valueOrThrow - 如果存在,返回值,否则抛出错误。

valueOrNil - 如果存在,返回值,否则返回 nil。

valueElse - 如果存在,返回值,否则返回您放入 else 的值。