arraysswiftcodable

Swift Converting Codable Variable to String Array


I'm following this tutorial on creating a collapsible TableView:

https://www.youtube.com/watch?v=Q8k9E1gQ_qg

He's loading a String array of names into the tableview like so:

struct ExpandableNames {
    
    var isExpanded: Bool
    let names: [String]
    
}

var twoDimensionalArray = [
        ExpandableNames(isExpanded: true, names: ["Amy", "Bill", "Zack", "Steve", "Jack", "Jill", "Mary"]),
        ExpandableNames(isExpanded: true, names: ["Carl", "Chris", "Christina", "Cameron"]),
        ExpandableNames(isExpanded: true, names: ["David", "Dan"]),
        ExpandableNames(isExpanded: true, names: ["Patrick", "Patty"]),
    ]

I would instead like to create the String array of names from my Codable User model's "name" variable:

 struct User: Codable {
        //var id: Int
        var user_id: Int
        var name: String
        
        static func endpointForUsers() -> String {
            return "users.php"
          
        }
    }

EDIT: In short... I have a [User] and I want a [String] made up of the name properties from the [User] array.

Could you please explain how I can then load all the names from my User codable as a String array? (Like the one in the tutorial.)

Thanks in advance!


Solution

  • If you have an array of User objects and want to convert it to an array of Strings from the name properties of each User you can use the map() function.

    Assuming you have 2 arrays of User objects:

    struct User: Codable {
            //var id: Int
            var user_id: Int
            var name: String
            
            static func endpointForUsers() -> String {
                return "users.php"
              
            }
        }
    }
    
    func userNames(_ users: [User]) -> [String] {
        return users.map { $0.name }
    }
    
    let users1: [User] = // Fetch users from a JSON file, a network call, or whatever
    let users2: [User] = // Fetch another array of users from somewhere.
    
    // MARK: - new code here
    var twoDimensionalArray = [
            // Create an ExpandableNames with the users from users1
            ExpandableNames(isExpanded: true, names: userNames(users1)),
    
            // Create an ExpandableNames with the users from users2
            ExpandableNames(isExpanded: true, names: userNames(users2)) ]
    

    (I wrote my answer in the form of a function for clarity, but given that this is a single line of code, it's probably cleaner and simpler to just use the map statement inline in your code.)