I was surfing in swift STD particularly in the "Int structure", and there is a function named
func encode(to encoder: Encoder) throws
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.
Thanks
As you may be aware, Int
conforms to Encodable which defines the encode(to:)
method that you have discovered. You can use an encoder such as a JSONEncoder or PropertyListEncoder to encode any type that conforms to the Encodable
protocol. For example:
let encoder = JSONEncoder()
let jsonData = try encoder.encode(5)
You don't need to worry about calling encode(to:)
on Int
directly. Your encoder should handle all of that under the hood.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.