Swift中Model的定义

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!)
  • 基于“ ObjectMapper” 的model定义中有几个参数就需要map几个参数,如果参数一多,就会显得繁琐。如果你想要简化代码,建议使用基于“HandyJSON”的model。

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.deserializeFrom(dict: dict.dictionaryObject! as NSDictionary)

你可能感兴趣的:(Swift中Model的定义)