Search code examples
arraysswiftstructure

How to acces array of structures in structure Swift


I have the following stucture:

struct Points : Codable {
    var name : String?
    var interests : [Interests]
    
    ///How do i get string or array of string that is equal to all interests
    
    var allInterestText : String ///???
}

struct Interests : Codable {
    var interest : Interest?
}

struct Interest : Codable{
    var name : String?
}

I've been trying to achieve that, but all my attempts have failed.


Solution

  • Try this for a single String:

    struct Points {
    
        // ...
    
        var allInterestText: String {
            interests.compactMap { $0.interest?.name }.joined(separator: " ")
        }
    }
    

    if you decide you want an Array instead, simple change the type and remove the .joined()