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

ios – Having issues with using map in Swift

[ad_1]

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.id = petDto.id
        self.category = Category(categoryDto: petDto.category)
        self.name = petDto.name
        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) {
        self.id = tagDTO.id
        self.name = tagDTO.name
    }
}

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] = petDto.map { PetDataModel(petDto: $0) }
            self?.petDataArray = listOfPets
            resultHandler(.success(listOfPets))
        case .failure:
            resultHandler(.failure(.serverError))
        }
    })
}

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 = model.name
        statusLabel.text = model.status?.rawValue
        tagsLabel.text = model.tags.name
        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

Thanks

[ad_2]

Source link

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments