打包 1.0.0

Pack 1.0.0

测试已测试
Lang语言 SwiftSwift
许可证 MIT
发布最新发布2017年12月
SwiftSwift 版本4.0
SPM支持 SPM

Anton Romanov 维护。



Pack 1.0.0

  • Istered

Pack

Build Status
Version
License
Platform
Carthage compatible

简介

Pack 是一个围绕 Encodable/Decodable 协议的包装器,让您的代码编写方式(几乎)与使用 ObjectMapper 一样,从而更方便地将现有的 ObjectMapper 代码迁移到 Pack。这个库的主要灵感来源是 ObjectMapper,因此您会发现一些协议和对象具有相同的名称和结构。它旨在使您能够轻松地将现有 ObjectMapper 代码迁移到 Pack

动机

您为什么要使用这个库呢?在某些情况下,Encodable/Decodable 的默认实现/代码生成可以让您获得很好的结果,同时让您的代码尽可能简洁。然而,如果您需要稍微自定义映射过程,您将写下很多类似的重复代码

class Item: Codable {
    let userId: String
    let position: Int
    let score: Int

    private enum CodingKeys: String, CodingKey {
        case userId = "id"
        case position
        case score
    }
    
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        userId = try container.decodeIfPresent(String.self, forKey: .userId) ?? ""
        position = try container.decodeIfPresent(Int.self, forKey: .position) ?? 0
        score = try container.decodeIfPresent(Int.self, forKey: .score) ?? 0
    }

    func encode(to encoder: Encoder) throws {
        let container = try encoder.container(keyedBy: CodingKeys.self)

        try encode(String.self, forKey: .userId)
        try encode(Int.self, forKey: .position)
        try encode(Int.self, forKey: .score)
    }
}

所以,Pack 让您可以编写

class Item: Mappable {
    var userId = ""
    var position = 0
    var score = 0
    
    required init() {
    }

    func mapping(map: Map) {
        userId <- map["id"]
        position <- map["position"]
        score <- map["score"]
    }
}

由于 Pack 仅仅是一个包装器,任何实现了 Mappable 协议的类也与已经使用 Encodable/Decodable 的代码兼容。

安装

CocoaPods

CocoaPods 是 Cocoa 项目的依赖项管理器。您可以使用以下命令进行安装

$ gem install cocoapods

要使用 CocoaPods 将 Pack 集成到您的 Xcode 项目中,请在您的 Podfile 中指定它

use_frameworks!

pod 'Pack'

然后,运行以下命令

$ pod install

Carthage

Carthage 是一个去中心化的依赖项管理器,它构建您的依赖项并提供二进制框架。

您可以使用 Homebrew 安装 Carthage,以下是一个命令

$ brew update
$ brew install carthage

要使用 Carthage 将 Pack 集成到您的 Xcode 项目中,请在您的 Cartfile 中指定它

github "istered/Pack"

运行 carthage update 来构建框架,然后将构建的 Pack.framework 拖拽到您的 Xcode 项目中。

作者

Anton Romanov

许可证

Pack 在 MIT 许可证下可用。有关更多信息,请参阅 LICENSE 文件。