菜鸟教程小白 发表于 2022-12-11 19:34:35

swift - 使用 Decodable 进行 JSON 解析时 optional 和 decodeIfPresent 有什么区别?


                                            <p><p>我第一次使用 Swift 4 的 <code>Codable</code> 协议(protocol),我无法理解 <code>Decodable</code> 中的 <code>decodeIfPresent</code> 的使用。 </p>

<pre><code>/// 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 -&gt; String?
</code></pre>

<p>这里建议它返回 <code>nil</code>,如果关联键不存在值。如果这是唯一的原因,那么它与可选属性有何不同,因为如果响应中不存在值,可选变量也设置为 <code>nil</code>。 </p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>这两行代码之间有一个微妙但重要的区别:</p>

<pre class="lang-swift prettyprint-override"><code>// Exhibit 1
foo = try container.decode(Int?.self, forKey: .foo)
// Exhibit 2
foo = try container.decodeIfPresent(Int.self, forKey: .foo)
</code></pre>

<p>Exhibit 1 将解析:</p>

<pre class="lang-json prettyprint-override"><code>{
&#34;foo&#34;: null,
&#34;bar&#34;: &#34;something&#34;
}
</code></pre>

<p>但<strong>不是</strong>:</p>

<pre class="lang-json prettyprint-override"><code>{
&#34;bar&#34;: &#34;something&#34;
}
</code></pre>

<p>虽然展览 2 会很高兴地解析两者。因此,在 <code>JSON</code> 解析器的正常用例中,您需要 <code>decodeIfPresent</code> 用于模型中的每个可选项。</p></p>
                                   
                                                <p style="font-size: 20px;">关于swift - 使用 Decodable 进行 JSON 解析时 optional 和 decodeIfPresent 有什么区别?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/48156758/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/48156758/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: swift - 使用 Decodable 进行 JSON 解析时 optional 和 decodeIfPresent 有什么区别?