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"])
How to filter an array of objects into different segments in Swift
A few things:
First, given that there a finite number of note types, I would model them as an enum instead of a String:
enum NoteType {
case atc
case imaging
case lab
}
You could always add an .unknown
case in the event that your backend provides a String that your client doesn't recognize. It may also be beneficial to give your NoteType
enum a raw type of String and have each rawValue correspond to the values your backend will provide.
Second, it's a bit unclear exactly what you want to accomplish with a UISegmentedControl
. My assumption is that you want a separate segment for each different type of Note? If that's the case, you could make the above enum conform to CaseIterable
and create a segment for each value found in NoteType
's allCases
array. (If you're going the route of having NoteType
s be Strings, then each segment's title could be set to every case's rawValue). It really all depends on what exactly you're trying to accomplish.
Third, I think in the end what you're wanting is three (or however many NoteType
s exist) separate arrays of Notes where each Note
is of the same type. That way you can determine what your UICollectionView
's datasource is depending on which segment of the UISegmentedControl
is selected. If that's what you're wanting (feel free to correct me), you can accomplish that via a simple filter call:
let sortedNotes = associatedNotes.sorted(by: {
$0.date.compare($1.date) == .orderedDescending
})
let atcNotes = sortedNotes.filter { $0.type == .atc }
let imagingNotes = sortedNotes.filter { $0.type == .imaging }
let labNotes = sortedNotes.filter { $0.type == .lab }
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 array of objects swift 4 then remove after
Use filter
:
let filteredImages = images.filter { $0.someproperty == whatYouWant }
Mutating for
-loops are something you want to avoid. Filtering is much safer.
Swift - Filtering an array of objects based upon its child array of orders?
You shouldn't try to map to Order, that is why you get the wrong type of result. Instead you can filter directly on Locomotive, for instance
locomotives.filter { !$0.order.isEmpty && $0.order.contains(where: { order in order.state > 0 }) }
How to filter array of items by another array of items in swift
Chose 1 in 2 option of return:
func filter(items: [Item], contains tags: [String]) -> [Item] {
items.filter { (item) -> Bool in
let tagNames = item.tags.map({ $0.name })
return tags.allSatisfy(tagNames.contains)
return Set(tags).isSubset(of: Set(tagNames))
}
}
Swift: Get indices of an array of objects filtered by a certain property
You could filter the indices
let selectedIndices = myObjects.indices.filter{selectedIds.contains(myObjects[$0].ID)}
Related Topics
Convert String to Cgfloat in Swift
How to Enable Swift Support for Existing Project in Flutter
Getting Timed Metadata in Swift iOS 8 from M3U8 Streaming Video
Xcode 11 Doesn't Recognize Core Data Entity
Is Swift Inout Parameter a Variable or a Pointer
Get Resource Url from Project Specific Path
Xcode 10 Beta 5 - Clang: Error: Linker Command Failed with Exit Code 1
Understanding @Binding in Swiftui
Create Instance of Class Known at Runtime in Swift
Value for Swift_Version Cannot Be Empty
Should Iboutlet Be Weak or Strong Var
Swift Draw Shadow to a Uibezier Path
Truncatingremainder VS Remainder in Swift
List All Available Audio Devices