Filter Array of [AnyObject] in Swift
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.
Filtering a Swift [AnyObject] array by type
It's better to use compactMap
for a nice one-liner:
let strings = grabBag.compactMap { $0 as? String }
Now strings
is of type [String]
.
How do I filter on an array of objects in Swift?
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"])
Filter array of Any based on variable
Make a protocol such as Rankable
, and make Person
and SportsMan
conform to it.
protocol Rankable {
var rank: Int { get }
}
Then make your array into an [Rankable]
(a.k.a. Array<Rankable>
) rather than [Any]
, and sort it like so:
self.persons.sort{ $0.rank < $1.rank }
Filter a Parse query with an Array of [AnyObject] in Swift
Here's a simple example that returns an array of matches in all fields:
func filterContentForSearchTextInAllFields(searchText: String) -> [String] {
var results = [String]()
for publication in publications {
for (key, value) in publication {
if (value as NSString).containsString(searchText) {
results.append(value)
}
}
}
return results
}
println(filterContentForSearchTextInAllFields("blog"))
This one only works on titles:
func filterContentForSearchText(searchText: String) -> [String] {
var results = [String]()
for publication in publications {
if let fullTitle = publication["fullTitle"] {
if (fullTitle as NSString).containsString(searchText) {
results.append(fullTitle)
}
}
}
return results
}
println(filterContentForSearchText("first"))
UPDATE
Here's a version for what you've asked in the comments:
func filterContentForSearchText(searchText: String) -> [[String:String]] {
var results = [[String:String]]()
for publication in publications {
if let fullTitle = publication["fullTitle"] as? String {
if (fullTitle as NSString).containsString(searchText) {
results.append(publication as! [String : String])
}
}
}
return results
}
println(filterContentForSearchText("first"))
Your "rows" are dictionaries: in the loop we assign each one to the "publication" variable, so we just take the one whose title matches the search terms then append it to an array of dictionaries.
How to remove dictionary[String:AnyObject] for array using filter function in swift?
Try using this
var globalCountArray = [AnyObject]()
var assetDictionary = [String:AnyObject]()
globalCountArray.append(assetDictionary as AnyObject)
let dict = [String:AnyObject]()
globalCountArray = globalCountArray.filter({ (obj) -> Bool in
if obj is[String:AnyObject] {
return (obj as! [String:AnyObject]) != dict
}
return false
})
--------- OR You can achieve the same via ----------
globalCountArray = globalCountArray.filter({ (obj) -> Bool in
if obj is[String:AnyObject] {
return (obj as! [String:AnyObject]) == dict
}
return true
})
You need to add this method to outside your class definition.
public func !=(lhs: [String: AnyObject], rhs: [String: AnyObject] ) -> Bool {
return !NSDictionary(dictionary: lhs).isEqual(to: rhs)
}
public func ==(lhs: [String: AnyObject], rhs: [String: AnyObject] ) -> Bool {
return NSDictionary(dictionary: lhs).isEqual(to: rhs)
}
Filter array of objects if property value exists in another array of objects swift
You are using some kind of reverse logic here. What you should be doing is this:
let filteredArr = meetingRoomSuggestions.filter { meeting in
return !bookingArray.contains(where: { booking in
return booking.dStart == meeting.dStart
})
}
In plain english: filter
meetings, leaving those that do not
have their dStart
values equal to the dStart
value of any object in the bookingArray
.
How to filter model array based on specific property
try this
let filteredArray = self.originalArray.filter({($0.itemCategory.localizedCaseInsensitiveContains(searchText))!})
Related Topics
Swift Xcode Index Freezing or Slow
Get Description of Emoji Character
Xcode 7.3.1 Hangs on "Copying Swift Standard Libraries"
Cllocationcoordinate2D Can't Be Instantiated
How to Get Line Number and Function Name in Swift Language
How to Check If Time Is Within a Specific Range in Swift
Class 'Viewcontroller' Has No Initializers in Swift
How We Can Get and Read Size of a Text with Geometryreader in Swiftui
Binary Operator '/' Cannot Be Applied to Two 'Double' Operands
How to Clear the Terminal Screen in Swift
Swiftui - Is There a Popviewcontroller Equivalent in Swiftui
Reference to Property in Closure Requires Explicit 'Self.' to Make Capture Semantics Explicit
Should Conditional Compilation Be Used to Cope With Difference in Cgfloat on Different Architectures
Swift 2 to 3 Migration for Prepareforsegue
Dismiss Keyboard with a Uitextview
Upvote/Downvote System Within Swift via Firebase
Intrinsiccontentsize() - Method Does Not Override Any Method from Its Superclass
Obervableobject Being Init Multiple Time, and Not Refreshing My View