【问题标题】:how to encode an Int in swift using the protocol Encoder如何使用协议编码器快速编码 Int
【发布时间】:2020-10-21 15:10:28
【问题描述】:

我在swift STD中冲浪,特别是在“Int结构”中,并且有一个名为

的函数
func encode(to encoder: Encoder) throws

https://developer.apple.com/documentation/swift/int/2894461-encode.

我看到了很多使用这个函数的例子,但是所有例子都包含结构和类,我想知道如何使用这个函数来编码一个 Int 类型的变量。

谢谢

【问题讨论】:

  • encoder.singleValueContainer().encode(5)

标签: ios swift


【解决方案1】:

您可能知道,Int 符合 Encodable,它定义了您发现的 encode(to:) 方法。您可以使用JSONEncoderPropertyListEncoder 等编码器对任何符合Encodable 协议的类型进行编码。例如:

let encoder = JSONEncoder()
let jsonData = try encoder.encode(5)

您无需担心直接在Int 上调用encode(to:)。您的编码器应该在后台处理所有这些。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    相关资源
    最近更新 更多