27
array1 = array1.filter{ $0.arrayInsideOfArray1.contains(array2[0]) }

Code above works but I'm trying to check if all the elements of $0.arrayInsideOfArray1 match with all the elements of array2 not just [0]

Example:

struct User {
    var name: String!
    var age: Int!
    var hasPet: Bool!
    var pets: [String]!
}

var users: [User] = []

users.append(User(name: "testUset", age: 43, hasPet: true, pets: ["cat", "dog", "rabbit"]))
users.append(User(name: "testUset1", age: 36, hasPet: true, pets:["rabbit"]))
users.append(User(name: "testUset2", age: 65, hasPet: true, pets:["Guinea pigs", "Rats"]))

let petArr = ["cat", "dog", "rabbit"]

users = users.filter { $0.pets.contains(petArr[0]) }

What I want is any user that has any pet listed in the petArr!

NikaE
  • 614
  • 1
  • 8
  • 15
  • You still haven't explained what results your expect to get with the code you posted. – rmaddy Apr 07 '17 at 02:37
  • print(user) prints: (name: "testUset", age: 43, hasPet: true, pets: ["cat", "dog", "rabbit"])] But the result I wanted to get in this case would be: User(name: "testUset", age: 43, hasPet: true, pets: ["cat", "dog", "rabbit"])] User(name: "testUset1", age: 36, hasPet: true, pets:["rabbit"])] – NikaE Apr 07 '17 at 02:42
  • So what you want is any user that has any pet listed in the `petArr`, correct? – rmaddy Apr 07 '17 at 02:46
  • Then please update your question to make that clear. Update your question to show the results you want. – rmaddy Apr 07 '17 at 02:49
  • 1
    @NikaE you should declare all properties of your structure as constantes and get rid of your IUO in all of them. structures don't require you to create its initializers. `struct User { let name: String let age: Int let hasPet: Bool let pets: [String] }` – Leo Dabus Apr 07 '17 at 14:27

2 Answers2

67

One approach is to update your filter to see if any value in pets is in the petArr array:

users = users.filter { $0.pets.contains(where: { petArr.contains($0) }) }

The first $0 is from the filter and it represents each User.

The second $0 is from the first contains and it represents each pet within the pets array of the current User.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
4

If elements inside the internal array are Equatable you can just write:

array1 = array1.filter{ $0.arrayInsideOfArray1 == array2 }

If they are not, you can make them, by adopting Equatable protocol and implementing:

func ==(lhs: YourType, rhs: YourType) -> Bool
Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
Zapko
  • 2,461
  • 25
  • 30