[英]how to encode an Int in swift using the protocol Encoder
I was surfing in swift STD particularly in the "Int structure", and there is a function named我在 swift STD 中冲浪,特别是在“Int 结构”中,并且有一个名为
func encode(to encoder: Encoder) throws
https://developer.apple.com/documentation/swift/int/2894461-encode . https://developer.apple.com/documentation/swift/int/2894461-encode 。
I saw many examples using this function, however all the examples contained structs and classes I was wondering how can I use this function to encode a variable of type Int.我看到很多使用这个函数的例子,但是所有的例子都包含结构和类,我想知道如何使用这个函数来编码一个 Int 类型的变量。
Thanks谢谢
As you may be aware, Int
conforms to Encodable which defines the encode(to:)
method that you have discovered.您可能知道,
Int
符合Encodable ,它定义了您发现的encode(to:)
方法。 You can use an encoder such as a JSONEncoder or PropertyListEncoder to encode any type that conforms to the Encodable
protocol.您可以使用JSONEncoder或PropertyListEncoder等编码器对符合
Encodable
协议的任何类型进行编码。 For example:例如:
let encoder = JSONEncoder()
let jsonData = try encoder.encode(5)
You don't need to worry about calling encode(to:)
on Int
directly.您无需担心直接在
Int
上调用encode(to:)
。 Your encoder should handle all of that under the hood.您的编码器应该在幕后处理所有这些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.