反思 0.18.1

反思 0.18.1

测试已测试
语言语言 SwiftSwift
许可证 MIT
发布最后发布2018年11月
SPM支持 SPM

Brad HiltonBrad Hilton 维护。



反思 0.18.1

  • Brad Hilton

Reflection

Swift License Slack Travis Codecov Codebeat

Reflection 提供了一个运行时高级反射的 API,包括动态类型构造。

使用

import Reflection

struct Person {
  var firstName: String
  var lastName: String
  var age: Int
}

// Reflects the instance properties of type `Person`
let props = try properties(Person.self)

var person = Person(firstName: "John", lastName: "Smith", age: 35)

// Retrieves the value of `person.firstName`
let firstName: String = try get("firstName", from: person)

// Sets the value of `person.age`
try set(36, key: "age", for: &person)

// Creates a `Person` from a dictionary
let friend: Person = try construct(dictionary: ["firstName" : "Sarah",
                                                "lastName" : "Gates",
                                                "age" : 28])

安装

import PackageDescription

let package = Package(
    dependencies: [
        .Package(url: "https://github.com/Zewo/Reflection.git", majorVersion: 0, minor: 15),
    ]
)

高级使用

// `Reflection` can be extended for higher-level packages to do mapping and serializing.
// Here is a simple `Mappable` protocol that allows deserializing of arbitrary nested structures.

import Reflection

typealias MappableDictionary = [String : Any]

enum Error : ErrorProtocol {
    case missingRequiredValue(key: String)
}

protocol Mappable {
    init(dictionary: MappableDictionary) throws
}

extension Mappable {

    init(dictionary: MappableDictionary) throws {
        self = try construct { property in
            if let value = dictionary[property.key] {
                if let type = property.type as? Mappable.Type, let value = value as? MappableDictionary {
                    return try type.init(dictionary: value)
                } else {
                    return value
                }
            } else {
                throw Error.missingRequiredValue(key: property.key)
            }
        }
    }

}

struct Person : Mappable {
    var firstName: String
    var lastName: String
    var age: Int
    var phoneNumber: PhoneNumber
}

struct PhoneNumber : Mappable {
    var number: String
    var type: String
}

let dictionary = [
    "firstName" : "Jane",
    "lastName" : "Miller",
    "age" : 54,
    "phoneNumber" : [
        "number" : "924-555-0294",
        "type" : "work"
    ] as MappableDictionary
] as MappableDictionary

let person = try Person(dictionary: dictionary)

支持

如果您需要任何帮助,您可以通过加入我们的 Slack 并前往 #help 通道来获得。或者,您可以在我们的主存储库中创建一个 Github 问题。在描述问题时,请确保添加足够详细的说明,并指定导致问题的模块以及重现步骤。

社区

Slack

整个 Zewo 代码库都采用 MIT 许可协议。通过为 Zewo 贡献,您正在为一群充满才华的 Swift 程序员贡献力量。加入我们吧,了解我们!请访问 Slack

许可协议

本项目采用 MIT 许可协议发布。有关详细信息,请参阅 LICENSE