tec*_*erd 23 swift swift4 codable decodable
我Codable第一次使用Swift 4的协议,我无法理解使用decodeIfPresentfrom Decodable.
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type.
public func decodeIfPresent(_ type: String.Type, forKey key: KeyedDecodingContainer.Key) throws -> String?
Run Code Online (Sandbox Code Playgroud)
这里建议nil如果值与关联键不存在则返回.如果这是唯一的原因,那么它与可选属性的区别,因为可选变量也设置为nilif值在响应中不存在.
Gun*_*ger 64
这两行代码之间有一个微妙但重要的区别:
// Exhibit 1
foo = try container.decode(Int?.self, forKey: .foo)
// Exhibit 2
foo = try container.decodeIfPresent(Int.self, forKey: .foo)
Run Code Online (Sandbox Code Playgroud)
图表1将解析:
{
"foo": null,
"bar": "something"
}
Run Code Online (Sandbox Code Playgroud)
但不是:
{
"bar": "something"
}
Run Code Online (Sandbox Code Playgroud)
而展览2将愉快地解析两者.因此,在JSON解析器的正常使用情况下,您需要decodeIfPresent模型中的每个可选项.
Fré*_*dda 13
我认为decodeifPresent如果您想使用 JSON 中可能缺少的属性的默认值,那么使用而不是可选属性是有意义的。
例如,让我们检查 3 种情况:
1. 所有键都存在于 JSON 中:
假设您必须解码此 JSON:
{
"project_names": ["project1", "project2", "project3"],
"is_pro": true
}
Run Code Online (Sandbox Code Playgroud)
您可以使用这个结构:
struct Program: Codable {
let projectNames: [String]
let isPro: Bool
}
Run Code Online (Sandbox Code Playgroud)
你将得到一个值等于 的Program对象。(我想你的解码器在这个例子的其余部分)isProtruekeyDecodingStrategy.convertFromSnakeCase
2. JSON 中缺少一些键,您可以在 Swift 中使用可选键:
{
"project_names": ["project1", "project2", "project3"]
}
Run Code Online (Sandbox Code Playgroud)
您现在可以使用这个结构:
struct Program: Codable {
let projectNames: [String]
var isPro: Bool?
}
Run Code Online (Sandbox Code Playgroud)
你将得到一个值等于 的Program对象。isPronil
如果 JSON 看起来像这样:
{
"project_names": ["project1", "project2", "project3"],
"is_pro": true
}
Run Code Online (Sandbox Code Playgroud)
那么isPro将是一个Bool?具有价值的true。也许这就是您想要的,但您可能希望有一个Bool默认值为false. 这就是decodeIfPresent有用的地方。
3. JSON 中缺少某些键,并且您需要一个在 Swift 中具有默认值的非可选属性:
如果您的结构如下所示:
struct Program: Codable {
let projectNames: [String]
var isPro: Bool = false
}
Run Code Online (Sandbox Code Playgroud)
那么如果 JSON 中不存在“is_pro”属性,您将收到解析错误。因为 Codable 期望找到一个值来解析 Bool 属性。
在这种情况下,一个好主意是使用 的初始化程序decodeIfPresent,如下所示:
struct Program: Codable {
let projectNames: [String]
let isPro: Bool
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.projectNames = try container.decode([String].self, forKey: .projectNames)
self.isPro = try container.decodeIfPresent(Bool.self, forKey: .isPro) ?? false
}
}
Run Code Online (Sandbox Code Playgroud)
这使您能够两全其美:
Bool,而不是一个Bool?属性false如果 JSON 中不存在该字段,您可以获得默认值。是的,@ Sweeper的评论是有道理的.
我将根据我的理解尝试解释它.
public class User : Decodable{
public var firstName:String
public var lastName:String
public var middleName:String?
public var address:String
public var contactNumber:String
public enum UserResponseKeys: String, CodingKey{
case firstName = "first_name"
case lastName = "last_name"
case middleName = "middle_name"
case address = "address"
case contactNumber = "contact_number"
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: UserResponseKeys.self)
self.firstName = try container.decode(String.self, forKey: .firstName)
self.lastName = try container.decode(String.self, forKey: .lastName)
self.middleName = try container.decodeIfPresent(String.self, forKey: .middleName)
self.address = try container.decode(String.self, forKey: .address)
self.contactNumber = try container.decode(String.self, forKey: .contactNumber)
}
}
Run Code Online (Sandbox Code Playgroud)
上面是我的User类,其中我标记middleName为可选参数,因为JSON响应可能不会middleName在响应中提供键值对,因此我们可以使用decodeIfPresent.
self.middleName = try container.decodeIfPresent(String.self, forKey: .middleName)
Run Code Online (Sandbox Code Playgroud)
而对于其他变量是必填字段,所以我们确定不需要使用可选字段.我们只decode使用那个,因为该方法不返回可选项.
public func decode(_ type: String.Type, forKey key: KeyedDecodingContainer.Key) throws -> String
Run Code Online (Sandbox Code Playgroud)
上面的decode函数返回String时decodeIfPresent返回String?,所以我们可以使用可选变量来存储它.
因此,最后的结论是,如果您不确定服务响应合同,或者您可能在不知情的decodeIfPresent情况下处理JSON响应和参数可能会发生变化的任何第三方服务,那么您可以使用它来处理响应中缺少特定参数和设置值作为nil.
| 归档时间: |
|
| 查看次数: |
7532 次 |
| 最近记录: |