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.
Videos
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.
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
Use contains instead:
let arr = ["Hello","Bye","Halo"]
let filtered = arr.filter { $0.contains("lo") }
print(filtered)
Output
["Hello", "Halo"]
Thanks to @user3441734 for pointing out that functionality is of course only available when you import Foundation
In Swift 3.0
let terms = ["Hello","Bye","Halo"]
var filterdTerms = [String]()
func filterContentForSearchText(searchText: String) {
filterdTerms = terms.filter { term in
return term.lowercased().contains(searchText.lowercased())
}
}
filterContentForSearchText(searchText: "Lo")
print(filterdTerms)
Output
["Hello", "Halo"]
contains() checks if a sequence contains a given element, e.g.
if a String contains a given Character.
If your intention is to find all books where the name contains the substring "rt", then you can use rangeOfString():
var arr = englishBooks.filter {
$0.nameOfBook.rangeOfString("rt") != nil
}
or for case-insensitive comparison:
var arr = englishBooks.filter {
$0.nameOfBook.rangeOfString("rt", options: .CaseInsensitiveSearch) != nil
}
As of Swift 2, you can use
nameOfBook.containsString("rt") // or
nameOfBook.localizedCaseInsensitiveContainsString("rt")
and in Swift 3 this is
nameOfBook.contains("rt") // or
nameOfBook.localizedStandardContains("rt") // or
nameOfBook.range(of: "rt", options: .caseInsensitive) != nil
Sorry this is an old thread. Change you code slightly to properly init your variable 'nameOfBook'.
class book{
var nameOfBook: String!
init(name: String) {
nameOfBook = name
}
}
Then we can create an array of books.
var englishBooks = [book(name: "Big Nose"), book(name: "English Future
Prime Minister"), book(name: "Phenomenon")]
The array's 'filter' function takes one argument and some logics, 'contains' function can take a simplest form of a string you are searching for.
let list1 = englishBooks.filter { (name) -> Bool in
name.contains("English")
}
You can then print out list1 like so:
let list2 = arr1.map({ (book) -> String in
return book.nameOfBook
})
print(list2)
// print ["English Future Prime Minister"]
Above two snippets can be written short hand like so:
let list3 = englishBooks.filter{ ($0.nameOfBook.contains("English")) }
print(list3.map({"\($0.nameOfBook!)"}))
struct Address {
var name: String
var imageURL: String
var address: String
}
let VIPArray = [["name": "John B"], ["name": "Sara K"]]
let AddressArray = [Address(name: "John B", imageURL: "johnb", address: "178 Main St."),
Address(name: "Dave H", imageURL: "daveh", address: "1011 Victoria St.."),
Address(name: "Sara K", imageURL: "sarak", address: "279 Maple Av."),
Address(name: "Niles K", imageURL: "nilesk", address: "45 King St."),
Address(name: "Ingrid G", imageURL: "ingridg", address: "33 Union St.")]
var filtered = [Address]()
for element in VIPArray {
for address in AddressArray {
if element["name"] == address.name {
filtered.append(address)
}
}
}
for record in filtered {
print(record)
}
OUTPUT:
Address(name: "John B", imageURL: "johnb", address: "178 Main St.")
Address(name: "Sara K", imageURL: "sarak", address: "279 Maple Av.")
Or:
let filtered: [Address] = AddressArray.filter { (address) -> Bool in
for vip in VIPArray {
if vip["name"] == address.name {
return true
}
}
return false
}
let VIPArray = [["name": "John B"], ["name": "Sara K"]]
struct Address {
let name: String
let imageURL: String
let address: String
}
let addressArray = [Address(name: "John B", imageURL: "johnb", address: "178 Main St."),
Address(name: "Dave H", imageURL: "daveh", address: "1011 Victoria St.."),
Address(name: "Sara K", imageURL: "sarak", address: "279 Maple Av."),
Address(name: "Niles K", imageURL: "nilesk", address: "45 King St."),
Address(name: "Ingrid G", imageURL: "ingridg", address: "33 Union St.")]
let myVips = addressArray.filter() {VIPArray.contains(["name":$0.name])}
You can just write
let result = words
.filter { $0.contains(keyword) }
.sorted { ($0.hasPrefix(keyword) ? 0 : 1) < ($1.hasPrefix(keyword) ? 0 : 1) }
Example
let words = ["apple", "workshops", "shopping", "sports", "parties", "pantry", "pen", "cat", "house"]
let keyword = "p"
let result = words
.filter { $0.contains(keyword) }
.sorted { ($0.hasPrefix(keyword) ? 0 : 1) < ($1.hasPrefix(keyword) ? 0 : 1) }
// ["pen", "pantry", "parties", "apple", "workshops", "shopping", "sports"]
Try this. Firstly, it filters the array to remove those elements that do not contain the search string, then uses a custom sort to prefer items that start with the search string. In general, use the Cartesian approach of splitting a problem into smaller sub-problems, rather than try to solve it all in one step.
let searchString = "p"
let array = ["apple", "workshops", "shopping", "sports", "parties", "pantry", "pen", "xyzzy"]
let filteredArray = array.filter({ $0.contains(searchString) })
filteredArray // drops xyzzy
let sortedArray = filteredArray.sorted(isOrderedBefore: {
switch ($0.hasPrefix(searchString), $1.hasPrefix(searchString)) {
case (true, true):
return $0 < $1
case (true, false):
return true
case (false, true):
return false
case (false, false):
return $0 < $1
}
})
sortedArray // "pantry", "parties", "pen", "apple", "shopping", "sports", "workshops"] as required
try this
let filteredArray = self.originalArray.filter({($0.itemCategory.localizedCaseInsensitiveContains(searchText))!})
You can try something like:
itemArray.filter({$0.itemCategory == "Test"})
$0 will present the object in the array and you can use it for every property in your object.