Object Mapper使我的值成为可选项

时间:2017-04-04 11:48:19

标签: swift mapping objectmapper

struct User: Mappable {

  init?(map: Map) {

  }

  mutating func mapping(map: Map) {
    token <- map["token"]
    email <- map["email"]
  }

  var token : String!
  var email : String!
}

我声明我的字符串是有条件包装的,这样我就可以直接使用out wrap,但是在将所有字符串映射到access之后我需要再次换行?

为什么需要再次换行?

1 个答案:

答案 0 :(得分:2)

You don't need the wrapping if you check the values in the initializer, something like this will work.

struct User: Mappable {

    var token: String
    var email: String

    init?(map: Map) {
        guard let token: String = map["token"].value(),
              let email: String = map["email"].value() else {

          print("User should have token and email")
          return nil
        }

        self.token = token
        self.email = email
    }

    mutating func mapping(map: Map) {
        token <- map["token"]
        email <- map["email"]
    }
}

Now you can use token and email in your code without wrapping