0

I’m getting a series of data from a json like it

   [
  {
   "name": "david",
    "gender": "Male"
  },
  {
    "name": "Sara",
    "gender": "Female"
  },
  {
    "name": "Philipp",
    "gender": "Male"
  },
  {
    "name": "Marry",
    "gender": "Female"
  }
]

I get this data and store them into one array

Lets call it names

Now I want to create two other arrays

femaleNames

maleNames

And I want to save all the female name in femaleNames and all the male names in maleNames based on the gender type of data. I don’t that how I can implement this condition in swift 5. Could you please help me? Thanks

1
  • Do you want just the names or do you want just the "people" of different genders split out? Commented Feb 14, 2020 at 21:21

2 Answers 2

1

Assuming you have a model struct for your data along these lines:

enum Gender: Decodable, String {
    case female = "Female"
    case male = "Male"
}

struct NameEntry: Decodable {
    let name: String
    let gender: Gender
}

and given a bunch of names in

var names: [NameEntry]

your can filter easily using

let femaleNames = names.filter { $0.gender == .female }
let maleNames = names.filter { $0.gender == .male }
Sign up to request clarification or add additional context in comments.

Comments

1

You can use filter over the array;


struct YourStruct: Decodable {
    let name: String
    let gender: String
}

let femaleNames = names.filter( { $0.gender == "Female"})
let maleNames = names.filter( { $0.gender == "Male"})

3 Comments

Might want to include a note in there about assuming that you've got the arrays encoded to some sort of struct/class that have a gender and maybe a name property on them.
Thank you so much, but how I can say if it’s male do that or if it’s female do that?
You should decode your JSON data to a struct and then using filter. I update it and add struct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.