Swfit学习

Swift中Model的定义

2018-08-13  本文已影响0人  古月思吉

1.基于“ ObjectMapper” 的model:
(0)第三方的导入(Podfile文件):

#根据SwiftLanguage的版本定义需要pod的版本
pod 'ObjectMapper', '~> 2.2.8'
pod 'SwiftyJSON', '~> 3.0’

(1)定义:

import UIKit
import ObjectMapper

class PayProductDetailModel: Mappable {
        
    var name: String?//产品名称
    var price: String?//产品价格,以元为单位
    var pay_type: [String]?
    var tipsModel: StudentInfoTipsModel?
    
    //用来展示的价格
    var priceShow: String? {
        guard price != nil else {
            return "¥600"
        }
        return "¥" + price!
    }
    
    required init?(map: Map) {
        
    }
    
    func mapping(map: Map) {
        name<-map["name"]
        price<-map["price"]
        pay_type<-map["pay_type"]
        tipsModel<-map["tips"]
    }
    
}

(2)dictionary转化成model:

import SwiftyJSON

self?.productDetailModel = PayProductDetailModel(JSON: data["data"].dictionaryObject!)

2.基于“ HandyJSON” 的model:
(0)第三方的导入(Podfile文件):

#根据SwiftLanguage的版本定义需要pod的版本
pod 'HandyJSON', '~> 4.1.1'
pod 'SwiftyJSON', '~> 3.0’

(1)定义:

import UIKit
import HandyJSON

class BaseModel: HandyJSON {

    required init() {
        
    }
    
}
import UIKit

class WordsTrainingItemModel: BaseModel {
    
    var title: String?
    var is_answer: Bool?//是否是答案,true:是、false:不是
    
}

(2)dictionary转化成model:

import SwiftyJSON
import HandyJSON

let model = JSONDeserializer<WordsTrainingItemModel>.deserializeFrom(dict: dict.dictionaryObject! as NSDictionary)
上一篇 下一篇

猜你喜欢

热点阅读