Sunday, April 2, 2023
HomeiOS Developmentios - Having issues with using map in Swift

ios – Having issues with using map in Swift


I got this issue with understating the map function in swift. I understand it creates an array of transformed objects, but when I have to use it, I think that map isn’t going to help me. Here is some code:

struct PetDataModel {
    var id: Int
    var category: Category?
    var name: String?
    var photoUrls: [String]?
    var tags: [Tags]?
    var status: Status?
    init(petDto: PetDTO) { =
        self.category = Category(categoryDto: petDto.category) =
        self.photoUrls = petDto.photoUrls
        for tag in petDto.tags ?? [] { // here I can have more then 1 Tag in my array, I could have 2 or more. For now it only get's 1 which is incorrect
            self.tags = [Tags(tagDTO: tag)] // petDto?.map { Tags(tagDTO: $0) }
        self.status = Status(rawValue: petDto.status.rawValue)

struct Tags {
    var id: Int
    var name: String?
    init(tagDTO: TagDTO) { = =

This is my dataModel, and I think I should change petDto to be an array, because I use this initializer to map data from DTO(which looks the same but without initializers) to dataModel. And I also need to be able to use map, but I only can use it with arrays…
Here is how I use it in my model:

private(set) var petDataArray: [PetDataModel]

 func downloadPetByStatus(resultHandler: @escaping (Result<[PetDataModel], ErrorType>) -> Void) {
    apiClient?.getPetByStatus(resultHandler: { [weak self] result in
        switch result {
        case .success(let petDto): // should I have array here?
            let listOfPets: [PetDataModel] = { PetDataModel(petDto: $0) }
            self?.petDataArray = listOfPets
        case .failure:

As you can see, I already use map in my model, but how do I change the for loop from my dataModel to work with map?

How do I get element of array with using map in this code and in general:

func setCellValues(model: PetDataModel) {
        nameLabel.text =
        statusLabel.text = model.status?.rawValue
        tagsLabel.text =
        categoryLabel.text = model.category?.name // Value of type '[Tags]?' has no member 'name'

Maybe I shouldn’t be getting the element with map, I once did it with forEach and was told to replace it with map since it’s more swifty.

Please help me



Source link



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments