0

I am getting a lot of data from my server.

To serialize it I use ModelMapper. I have lots of Mappable objects, so I need a function that would be able to map any kind of mappable data. Something like this:

func serializeData(of type: Mappable.Type) -> [Mappable]? {
     return try? response?.map(to: [type].self)
}

My issue is that map(:) method requires [Mappable].Type as input. [type].self however is [Mappable.Type]. I am getting lost here. Please help

1 Answer 1

5

Passing the type as foo.Type is a very objective-c-ish pattern.

In Swift I'd prefer a generic solution, something like

func serializeData<T : Mappable>() -> [T]? {
     return try? response?.map(to: [T].self)
}

or still swiftier

func serializeData<T : Mappable>() throws -> [T] {
     return try response?.map(to: [T].self) ?? []
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'm always impressed with your responses. Do you have a Swift blog or anything similar?
@D.Greg Thanks. No, I haven't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.