KeyedAPIParameters
Swift中API参数的一个概念。
要求
- Xcode 9.3+
- Swift 4.1+
- iOS 8+
用法
此框架围绕几个主要组件构建,我将在下面进行说明。
APIParamConvertible
APIParamConvertible是一个协议,它定义了一个对象,可以将该对象安全地转换为给定的HTTP方法值。我们传递HTTP方法的原因是不同的HTTP方法可能需要不同的输出。例如,GET请求需要String
对象,而POST请求可以使用任何可以被编码为JSON的对象。
public protocol APIParamConvertible {
func value(forHTTPMethod method: HTTPMethod) -> Any
}
通过查看APIParamConvertible.swift
,您可以看到内置的可转换类型。
APIParameters
APIParameters
是您可以使参数符合的第一个级别的协议。存在APIParameters
的原因是它允许您有String
键,而无需创建枚举,这可能是某些人的首选。
public protocol APIParameters: APIParamConvertible {
func toParamDictionary() -> [String : APIParamConvertible]
}
一个基本的例子将是
import KeyedAPIParameters
struct Object {
let stringProperty: String
}
extension Object: APIParameters {
func toParamDictionary() -> [String : APIParamConvertible] {
return ["stringProperty" : stringProperty]
}
}
KeyedAPIParameters
KeyedAPIParameters
是您可以使参数符合的最高级别的协议。此协议强制您为参数键定义枚举。
public protocol KeyedAPIParameters: APIParameters {
associatedtype Key: ParamJSONKey
func toKeyedDictionary() -> [Key: APIParamConvertible]
}
一个基本的例子将是
import KeyedAPIParameters
struct Object {
let stringProperty: String
}
extension Object: KeyedAPIParameters {
enum Key: String, ParamJSONKey {
case stringProperty
}
func toKeyedDictionary() -> [Key : APIParamConvertible] {
return [.stringProperty : stringProperty]
}
}
完整示例
import KeyedAPIParameters
struct InnerObject {
let innerStringProperty: String
}
extension InnerObject: KeyedAPIParameters {
enum Key: String, ParamJSONKey {
case innerStringProperty
}
func toKeyedDictionary() -> [Key : APIParamConvertible] {
return [.innerStringProperty : innerStringProperty]
}
}
struct Object {
let stringProperty: String
let intProperty: Int
let floatProperty: Float
let doubleProperty: Double
let boolProperty: Bool
let optionalProperty: String?
let arrayProperty: [String]
let nestedProperty: InnerObject
}
extension Object: KeyedAPIParameters {
enum Key: String, ParamJSONKey {
case stringProperty
case intProperty
case floatProperty
case doubleProperty
case boolProperty
case optionalProperty
case arrayProperty
case nestedProperty
}
func toKeyedDictionary() -> [Key : APIParamConvertible] {
return [
.stringProperty: stringProperty,
.intProperty: intProperty,
.floatProperty: intProperty,
.doubleProperty: doubleProperty,
.boolProperty: boolProperty,
.optionalProperty: optionalProperty,
.arrayProperty: arrayProperty,
.nestedProperty: nestedProperty
]
}
}