Swift使用編解碼庫Codable的過程詳解
Codable 是 Swift 引入的全新的編解碼庫,使開發(fā)者更方便的解析JSON 或 plist 文件。支持枚舉、結(jié)構(gòu)體和類。
Codable協(xié)議定義
Codable代表一個同時符合 Decodable 和 Encodable 協(xié)議的類型,即可解碼且可編碼的類型。
typealias Codable = Decodable & Encodable public protocol Decodable { public init(from decoder: Decoder) throws } public protocol Encodable { public func encode(to encoder: Encoder) throws }
Codable從 Swift 4 開始引入,包含了 Encoder 和 Decoder 協(xié)議和他們的兩個實現(xiàn) JSONEncoder、JSONDecoder 和 PropertyListEncoder、PropertyListDecoder。
其中 Codable 及其相關(guān)協(xié)議放在了標準庫中,而具體的 Encoder、Decoder 類放在了 Foundation 框架中。
JSON 和 模型的相互轉(zhuǎn)換
蘋果提供了 JSONEncoder
和 JSONDecoder
這兩個結(jié)構(gòu)體來方便得在 JSON 數(shù)據(jù)和自定義模型之間互相轉(zhuǎn)換。蘋果可以利用一些系統(tǒng)私有的機制來實現(xiàn)轉(zhuǎn)換,而不需要通過 OC Runtime
。
只要讓自己的數(shù)據(jù)類型符合 Codable 協(xié)議,就可以用系統(tǒng)提供的編解碼器進行編解碼。
struct User: Codable { var name: String var age: Int }
解碼(JSON Data -> Model):
let user = JSONDecoder().decode(User.self, from: jsonData)
編碼(Model -> JSON Data):
let jsonData = JSONEncoder().encode(user)
字典 和 模型的相互轉(zhuǎn)換
將模型用JSONEncoder的encode轉(zhuǎn)成Data,然后再用JSONSerialization反序列化成Dictionary對象。
struct User: Codable { var name: String? var age: Int? static func convertFromDict(dict: NSDictionary) -> User? { var user: User? do { let data = try JSONSerialization.data(withJSONObject: dict, options: []) let decoder = JSONDecoder() user = try decoder.decode(User.self, from: data) } catch { print(error) } return user } func convertToDict() -> NSDictionary? { var dict: NSDictionary? do { let encoder = JSONEncoder() let data = try encoder.encode(self) dict = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary } catch { print(error) } return dict } }
到此這篇關(guān)于Swift使用編解碼庫Codable的文章就介紹到這了,更多相關(guān)Swift編解碼庫Codable內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
iOS Swift UICollectionView橫向分頁滾動,cell左右排版問題詳解
UICollectionView是iOS中比較常見的一個控件,這篇文章主要給大家介紹了關(guān)于iOS Swift UICollectionView橫向分頁滾動,cell左右排版問題的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面隨小編來一起學習學習吧。2017-12-12使用Swift實現(xiàn)iOScollectionView廣告無限滾動效果(DEMO)
本文給大家分享使用Swift實現(xiàn)iOScollectionView廣告無限滾動效果(DEMO),非常不錯,具有一定的參考借鑒價值,感興趣的朋友一起看看吧2016-11-11Swift操作Quartz 2D進行簡單的繪圖與坐標變換的教程
這篇文章主要介紹了Swift操作Quartz 2D進行簡單的繪圖與坐標變換的教程,Quartz 2D是Core Graphics框架中的一個重要組件,經(jīng)常被Mac OS或和iOS開發(fā)者用來繪圖,需要的朋友可以參考下2016-04-04Swift利用CoreData如何存儲多種數(shù)據(jù)類的通訊錄
這篇文章主要給大家介紹了關(guān)于Swift利用CoreData如何存儲多種數(shù)據(jù)類的通訊錄的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧。2017-12-12