Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift: How to merge several sets of String?

Hello I have this case:

enum Test {
    static let all: [Test] = [.a, .b, .c]
   
    case a, b, c

    var chars: Set<String> {
        switch self {
            case .a: 
                return ["a", "b", "c"]
            case .b: 
                return ["d", "e", "f"]
            case .c: 
                return ["g", "h", "i"]
        }
    }
}

I would like to create a set that maps all the chars from all the cases, so the result would be:

["a", "b", "c", "d", "e", "f", "g", "h", "i"]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried this:

static var allCharacters: Set<String> {
    return Test.all
        .joined()
        .flatMap { $0.chars }
}

But this doesn’t work. What should I do?

Thank you for your help

>Solution :

You can try

 static var allCharacters: Set<String> {
     return Set(Test.all.flatMap { $0.chars })
 }

OR

 static var allCharacters: Set<String> {
     let res =  Test.all.map { $0.chars }
     return res.reduce(into: Set()) { partialResult, arr in
         partialResult = partialResult.union(arr)
     }
 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading