arraysswiftdictionaryclosures

Take keys from Dictionary and map them to an array


I'm trying to build a closure that does what my title says. My code runs but it does not print what I expected.

var names: [String] = []
var namesAndAges = ["Tom": 25, "Michael": 35, "Harry": 28, "Fabien": 16]

var ofAge = namesAndAges.filter { namesAndAges in namesAndAges.value > 18 }

var addNames = ofAge.map { ofAge in names.append(ofAge.key) }

print(addNames) //this prints [(), (), ()]

Solution

  • Basically you are misusing filter and map methods. Try this:

    var names: [String] = []
    var namesAndAges = ["Tom": 25, "Michael": 35, "Harry": 28, "Fabien": 16]
    
    var ofAge = namesAndAges.filter { $0.value > 18 }
    
    var addNames = ofAge.map { $0.key }
    
    print(addNames) //this prints ["Michael", "Harry", "Tom"]