UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 Superwall

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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.