Swift - 从字典(或者Alamofire)直接创建Model文件的工具
生活随笔
收集整理的這篇文章主要介紹了
Swift - 从字典(或者Alamofire)直接创建Model文件的工具
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Swift - 從字典(或者Alamofire)直接創建Model文件的工具
?
效果
1. 常規生成model的方式
2. 通過debug創建model的方式
?
?
特性
1. 可以處理JSON格式的字典數據
?
2. 可以處理本地的json數據
?
3. 可以處理Alamofire生成的json格式返回數據
?
4. 生成的Models繼承自NSObject,所有方法均系系統方法,沒有任何接口污染,后續升級不存在版本兼容問題(以下是一個生成的Model的示例)
// // AlamofireModel.swift // // http://www.cnblogs.com/YouXianMing/ // https://github.com/YouXianMing // // Copyright (c) YouXianMing All rights reserved. // import Foundation// MARK: [Class] AlamofireModelclass AlamofireModel: NSObject {// MARK: Stored propeties.//----------------------------------------------------------------------------- var origin : String?var url : String?var args : ArgsModel?var headers : HeadersModel?// MARK: Init methods.//-----------------------------------------------------------------------------/**Init with dictionary.- parameter dictionary: The json data dictionary.- returns: The instance.*/init?(dictionary : [String : AnyObject]?) {super.init()if let _ : [String : AnyObject] = dictionary { setValuesForKeysWithDictionary(dictionary!) } else { return nil}}/**Override init.- returns: The instance.*/override init() {super.init()}// MARK: SetValueForKey & setValueForUndefinedKey.//-----------------------------------------------------------------------------/**Sets the property of the receiver specified by a given key to a given value.- parameter value: The value for the property identified by key.- parameter key: The name of one of the receiver's properties.*/override func setValue(value: AnyObject?, forKey key: String) {// To ignore Null value.guard value != nil else {return}// Dictionary: argsif key == "args" {let dictionary = value as! [String : AnyObject]let model = ArgsModel(dictionary: dictionary)super.setValue(model, forKey: key)return}// Dictionary: headersif key == "headers" {let dictionary = value as! [String : AnyObject]let model = HeadersModel(dictionary: dictionary)super.setValue(model, forKey: key)return}super.setValue(value, forKey: key)}/**Invoked by setValue:forKey: when it finds no property for a given key.- parameter value: The value for the key identified by key.- parameter key: A string that is not equal to the name of any of the receiver's properties.*/override func setValue(value: AnyObject?, forUndefinedKey key: String) {// [Example] change property 'id' to 'userId'.//// if key == "id" {//// userId = value as? NSNumber// return// } print("[??] The file '\(self.classForCoder).swift' has an undefined key '\(key)', and the key's type is \(value?.classForCoder).")} }?
源碼
https://github.com/YouXianMing/Create-Swift-JSON-Model/tree/master
?
轉載于:https://www.cnblogs.com/YouXianMing/p/5814352.html
總結
以上是生活随笔為你收集整理的Swift - 从字典(或者Alamofire)直接创建Model文件的工具的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode Reverse Vow
- 下一篇: Spring-----多环境中加载资源配