class book{ var nameOfBook: String! } var englishBooks=[book(),book(),book()] var arr = englishBooks.filter { contains($0.nameOfBook, "rt") }
I'm using this filter but with error cannot invoke filter with an argument
Example 1: Swift Array filter() This is a short-hand closure that checks whether all the elements in the array have the prefix "N" or not. $0 is the shortcut to mean the first parameter passed into the closure. And finally, all the elements that start with "N" are stored in the result variable.
To filter elements of a Swift Array, call filter() method on this array and pass the predicate/condition to the filter() method. filter() method returns a new array with the elements of the original array, that satisfy the given condition.
To filter strings in a Swift String Array based on length, call filter() method on this String Array, and pass the condition prepared with the string length as argument to the filter() method. filter() method returns an array with only those elements that satisfy the given predicate/condition.
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!)"}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With