在swift中使用Moya无法解析除字符串之外的变量

时间:2017-12-06 03:27:45

标签: ios swift moya

我正在使用Swift的iOS项目。我使用Moya框架进行API处理和解析。它完美地运作。但是当我尝试解析除字符串以外的变量时,它会显示错误:

  

“在调用”

中缺少参数'转换'的参数

这是我的mapper类

import Mapper

class MyMapperClaa:Mappable {
    var dateVariable: NSDate?

    required init(map: Mapper) throws{
        try dateVariable = map.from("date")
    }
}

2 个答案:

答案 0 :(得分:2)

为Date创建了一个扩展,它为我工作

extension Date:Convertible
{
    public static func fromMap(_ value: Any) throws -> Date {
        guard let rawDate = value as? String else {
            throw MapperError.convertibleError(value: value, type: Date.self)
        }
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"

        if let date = dateFormatter.date(from: rawDate)  {
            return date
        } else {
            throw MapperError.convertibleError(value: value, type: Date.self)
        }


    }

}

答案 1 :(得分:1)

抱歉,您正在使用此库:https://github.com/lyft/mapper。从那里的例子:

private func extractDate(object: Any?) throws -> Date {
  guard let rawDate = object as? String else {
    throw MapperError.convertibleError(value: object, type: Date.self)
  }
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "your date format"

    if let date = dateFormatter.date(from: rawDate)  {
        return date
    } else {
      throw MapperError.convertibleError(value: object, type: Date.self)
    }

}

struct DateModel: Mappable {
  let date: Date

  init(map: Mapper) throws {
    try date = map.from("date", transformation: extractDate)
  }
}