LAST CHANCE: Save 50% on all my Swift books and bundles! >>

SOLVED: Array Filtering

Forums > SwiftUI

Let's say I have an array of objects, like so:

  "name": "david",
  "type": "human"
  "name": "chris",
  "type": "human"
  "name": "thor",
  "type": "god"
  "name": "wolverine",
  "type": "mutant"

Now I have another array, like so:

["human", "puppy", "automobile"]

How can I get all the objects from the first array that have a type value that exists in the second array?


Assuming the shape of your data object from that JSON:

import Foundation

struct CharacterData {
    let name: String
    let type: String

//presumably the data would normally be loaded from some JSON
//but for sake of example I'm just building it manually
let characters: [CharacterData] = [
    CharacterData(name: "David", type: "human"),
    CharacterData(name: "Chris", type: "human"),
    CharacterData(name: "Thor", type: "god"),
    CharacterData(name: "Wolverine", type: "mutant"),

let filteredCharacters = characters.filter {
    ["human", "puppy", "automobile"].contains($0.type)





Just a follow-up to say that this is exactly what I needed and works perfectly. Thanks again.


Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until July 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.