Home > database >  Swift - Append data from a struct to an array
Swift - Append data from a struct to an array

Time:11-04

I am trying to append data from a struct to an array.
After searching in Google I found that I have to map the data from struct to the array but maybe I don't do it right.

The data comes from an API.

My class of struct is the following

Models

import Foundation
// MARK: - Nft
struct Nft: Codable{
    let id:Int
    let image_url:String
    let name:String
    let creator: Creator
}

// MARK: - Icon
struct Icon:Codable{
    let image_url:String
}

// MARK: - Creator
struct Creator: Codable {
    let user: User
    let profileImgURL: String
 
    enum CodingKeys: String, CodingKey {
        case user
        case profileImgURL = "profile_img_url"
    }
}

// MARK: - User
struct User: Codable {
    let username: String?

}

In my main class I have the followings:

 func downloadJSON(completed: @escaping () -> ()) {
        let url = URL(string: "https://public.arx.net/~chris2/nfts.json")
        
        URLSession.shared.dataTask(with: url!) { [self] data, response, error in
            
            if error == nil {
                do {
                 
                    self.nfts = try JSONDecoder().decode([Nft].self, from: data!)
                
                    nfts.forEach { nft in
                        let creators = nfts.map { _ in nft.creator }
                        self.data.append(.type1(creators: creators))
                    }
                    
                    
                    self.nfts.forEach { nft in
                        self.data.append(.type2(nft: nft))
                    }
                    
                    DispatchQueue.main.async {
                        completed()
                    }
                }
                catch {
                    print("error fetching data from api")
                }
            }
        }.resume()
    }
}
enum DataEnum {
    case type1(creators: [Creator])
    case type2(nft: Nft)
}



struct Constants {
    static let url = "https://public.arx.net/~chris2/nfts.json"
}


I just want to fill an array of creators with the data from nft.creator that include profileImgURL and the username

CodePudding user response:

I suppose you have a var data: [DataEnum] = [] that you didn't post. To get the creators you can do

let creators = nfts.map(\.creator)

  • Related