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
Answer from Martin R on Stack Overflowcontains() 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!)"}))
I have an array of Match objects [Match] with a string property of matchID. I also have an array of strings.
I would like to remove the Match object where matchID equals any string in the array.
I currently have:
var matches = [Match]
var matchIDsToDelete = [String]
for match in matches {
for id in matchIDsToDelete {
if match.matchID == id {
// remove that item from array
}
}
}My concern is removing the object from the array as I'm enumerating. I believe there will be consequences. Any suggestions? I would also love a functional solution as I'm currently reading more about functional programming.
Thanks!
Videos
This is what I have working in a playground, any reason why this is no good?
class Book {
var author = String()
init(author:String){
self.author = author
}
}
var allBooks: [Book] = []
allBooks.append(Book(author: "John Smith"))
allBooks.append(Book(author: "Arthur Price"))
allBooks.append(Book(author: "David Jones"))
allBooks.append(Book(author: "Somebody Else"))
let authors = ["Arthur Price", "David Jones"]
let filteredBooks = allBooks.filter({authors.contains($0.author)})
filteredBooks // [{author "Arthur Price"}, {author "David Jones"}]
You could also use something like
let authorsAndBooks = authors.map {
(authorName) -> (String, [Book])
in (authorName,
allBooks.filter({ $0.author == authorName })
)
}
This will array of tuples with the first element being the author name and the second element an array of his books, in case an author wrote more than one book.
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
So I quickly did this to help out, if someone can improve that's fine I'm just trying to help.
I made a struct for the books
struct Book {
let title: String
let tag: [String]
}
Created an array of those
var books: [Book] = []
Which is empty.
I created a new object for each book and appended to books
let dv = Book(title: "The Da Vinci Code", tag: ["Religion","Mystery", "Europe"])
books.append(dv)
let gdt = Book(title: "The Girl With the Dragon Tatoo", tag: ["Psychology","Mystery", "Thriller"])
books.append(gdt)
let fn = Book(title: "Freakonomics", tag: ["Economics","non-fiction", "Psychology"])
books.append(fn)
So you've three objects in the books array now. Try to check with
print (books.count)
Now you want to filter for Psychology books. I filtered the array for tags of Psychology - are filters ok for you?
let filtered = books.filter{ $0.tag.contains("Psychology") }
filtered.forEach { print($0) }
Which prints the objects with your two Psychology books
Book(title: "The Girl With the Dragon Tatoo", tag: ["Psychology", "Mystery", "Thriller"])
Book(title: "Freakonomics", tag: ["Economics", "non-fiction", "Psychology"])
Representing the books as an array of tuples with named parameters title and tags for book title and tags respectively.
let books:[(title:String, tags:String)] = [
(title: "The Da Vinci Code", tags: "Religion, Mystery, Europe"),
(title: "The Girl With the Dragon Tatoo", tags: "Psychology, Mystery, Thriller"),
(title: "Freakonomics", tags: "Economics, non-fiction, Psychology")
]
You want to search for tag Psychology
let searchedTag = "Psychology"
We can use filter function to filter out the items in the books array that only contains the tag we are looking for.
let searchedBooks = books.filter{ $0.tags.split(separator: ",").map{ return $0.trimmingCharacters(in: .whitespaces) }.contains( searchedTag ) }
print(searchedBooks)
Inside the filter method, we have created an array of tag items from book tags using split(separator: Character) method. Next, using map function, we remove the leading and trailing whitespaces from each tag. Finally, using .contains(element) method, we test if the tag we are looking for is in this array. Only the tuples passing this test are returned and the others will be filtered out.
The result is:
[(title: "The Girl With the Dragon Tatoo", tags: "Psychology, Mystery, Thriller"), (title: "Freakonomics", tags: "Economics, non-fiction, Psychology")]
Your array, objects, is an array of PFObject objects. Thus, to filter the array, you might do something like:
let filteredArray = objects.filter() {
if let type = ($0 as PFObject)["Type"] as String {
return type.rangeOfString("Sushi") != nil
} else {
return false
}
}
My original answer, based upon an assumption that we were dealing with custom Restaurant objects, is below:
You can use the filter method.
Let's assume Restaurant was defined as follows:
class Restaurant {
var city: String
var name: String
var country: String
var type: [String]!
init (city: String, name: String, country: String, type: [String]!) {
...
}
}
So, assuming that type is an array of strings, you'd do something like:
let filteredArray = objects.filter() {contains(($0 as Restaurant).type, "Sushi")}
If your array of types could be nil, you'd do a conditional unwrapping of it:
let filteredArray = objects.filter() {
if let type = ($0 as Restaurant).type as [String]! {
return contains(type, "Sushi")
} else {
return false
}
}
The particulars will vary a little depending upon your declaration of Restaurant, which you haven't shared with us, but hopefully this illustrates the idea.
Swift 3 Solution
Use the filter method on an array.
let restaurants: [Restaurants] = [...]
restaurants.filter({(restaurant) in
return Bool(restaurant.type == "sushi")
})
or return Bool(restaurant.type.contains("sushi")) if type is an array.