我第一次使用Swift 4中的Codable
协议,我无法理解Decodable
中decodeIfPresent
的用法.
/// 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?
在这里,它建议返回nil
,如果值与相关键不存在.如果这是唯一的原因,那么它与可选属性有何不同,因为如果响应中不存在值,可选变量也会设置为nil
.