[英]How do I encode [Character : Int] property using NSCoder in Swift 3?
[英]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:)
方法。 您可以使用JSONEncoder或PropertyListEncoder等編碼器對符合Encodable
協議的任何類型進行編碼。 例如:
let encoder = JSONEncoder()
let jsonData = try encoder.encode(5)
您無需擔心直接在Int
上調用encode(to:)
。 您的編碼器應該在幕后處理所有這些。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.