Reputation: 438
Here is my code:
var parentList = [String]()
for user in MPUser.array {
if user.childParent == "parent" {
parentList.append(user.firstName)
}
}
guard parentList.contains((selectedSecondJob?.assigned)!) else {
print("payday has to be a parent, yo!")
return
}
It works, but I know I can make it more "Swifty" by using a higher order function like flatMap.
Here's what I tried:
let parentListTEST = MPUser.array.flatMap({ $0.childParent })
But it returns an array of Characters, not Strings. Why? The MPUser array is an array of structs that clearly defines the "parent" parameter as a String, not Character.
How do I get a new array from my MPUser array that just has the names of the parents as Strings and not Characters?
Upvotes: 0
Views: 165
Reputation: 100503
You can try either
let parentListTEST = MPUser.array.filter { $0.childParent == "childParent" }.map { $0.firstName }
Or
let parentListTEST = MPUser.array.compactMap { $0.childParent == "childParent" ? $0.firstName : nil }
Upvotes: 1
Reputation: 63271
Use map
.
flatMap
flattens nested collections. You're mapping over a list of User
s, getting an array of childParent
String
s (which are themselves collections of Character
), which flatMap
is flattening out into a single array.
You just want the mapping without the flattening, so just use map
.
Upvotes: 1