簡體   English   中英

如何使用協議 Encoder 在 swift 中對 Int 進行編碼

[英]how to encode an Int in swift using the protocol Encoder

我在 swift STD 中沖浪,特別是在“Int 結構”中,並且有一個名為

func encode(to encoder: Encoder) throws

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

我看到很多使用這個函數的例子,但是所有的例子都包含結構和類,我想知道如何使用這個函數來編碼一個 Int 類型的變量。

謝謝

您可能知道, Int符合Encodable ,它定義了您發現的encode(to:)方法。 您可以使用JSONEncoderPropertyListEncoder等編碼器對符合Encodable協議的任何類型進行編碼。 例如:

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

您無需擔心直接在Int上調用encode(to:) 您的編碼器應該在幕后處理所有這些。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM