tristanhimmelman / ObjectMapper

Simple JSON Object mapping written in Swift
MIT License
9.13k stars 1.03k forks source link

Automatic String casting to basic types #1100

Open mojidabckuu opened 4 years ago

mojidabckuu commented 4 years ago

Your JSON dictionary:

{
  "id": "1"
}

Your model:

struct Repo: Mappable {
  var id: Int = 0

  init(_ map: Map) {
    id <- map["id"]
  }
}

What you did:

let repo = Mapper<Repo>().map(myJSONDictionary)

What you expected:

print(repo.id) // prints 1 not 0

What you got:

print(repo.id) // prints 0

Hey there! Thanks for the awesome tool to map the data! Above is a use case when we need to handle string values for basic types. I know, I know that it would be cool to use transforms, but it is not elegant solution to handle a such case. The proposal: Simply do next steps

  1. Create a protocol
    protocol StringInitiable { 
    init?(stringValue: String) 
    }
  2. Add basic extensions
    extension Int: StringInitiable {
    init?(stringValue: String) {
    guard let value = Int(stringValue) else { return nil }
    self = value
    }
    }
  3. Edit operators to handle <T: StringInitiable>
  4. Edit Map's value to handle a case
    if let v = currentValue as? String { return T.init(stringValue: currentValue)

Point me if I wrong but it would be awesome to automatically cast String to basic types without any effort for the end user and moreover without breaking changes.

I am happy to make the PR

Cheers, Vlad