how to check if a property value exists in array of objects in swift
You can filter the array like this:
let results = objarray.filter { $0.id == 1 }
that will return an array of elements matching the condition specified in the closure - in the above case, it will return an array containing all elements having the id
property equal to 1.
Since you need a boolean result, just do a check like:
let exists = results.isEmpty == false
exists
will be true if the filtered array has at least one element
Swift: Determine if a array of custom objects contains a particular string
Add something like this
func contains(make: String) -> Bool {
carArray.compactMap(\.make).contains(make)
} // returns true in your case for "BMW"
This has two parts. First, I am mapping the array of Car objects to an array of String?
by mapping over the make key path. Since this may have nil values, I am using compactMap
to remove the nil values.
If you are going to be doing this a lot and don't want the overhead of mapping and checking every time then create something to store your cars. Something like this:
struct Car {
var make: String?
var model: String?
var year: Double?
}
struct CarStore {
private(set) var storage: [Car] = .init()
private var makes: Set<String> = .init()
mutating func add(car: Car) {
storage.append(car)
car.make.map { makes.insert($0) } // map to run the closure only if make is not nil
}
func contains(make: String) -> Bool {
makes.contains(make)
}
}
var store = CarStore()
store.add(car: Car(make: "Audi", model: "S5", year: 2015))
store.add(car: Car(make: "BMW", model: "X3", year: 2016))
store.add(car: Car(make: "Honda", model: "Accord", year: 2018))
store.contains(make: "BMW") // -> true
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
.
Swift - Check if array contains element with property
Yes,
if things.contains(where: { $0.someProperty == "nameToMatch" }) {
// found
} else {
// not
}
How to check if an element is in an array
Swift 2, 3, 4, 5:
let elements = [1, 2, 3, 4, 5]
if elements.contains(5) {
print("yes")
}
contains()
is a protocol extension method of SequenceType
(for sequences of Equatable
elements) and not a global method as in
earlier releases.
Remarks:
- This
contains()
method requires that the sequence elements
adopt theEquatable
protocol, compare e.g. Andrews's answer. - If the sequence elements are instances of a
NSObject
subclass
then you have to overrideisEqual:
, see NSObject subclass in Swift: hash vs hashValue, isEqual vs ==. - There is another – more general –
contains()
method which does not require the elements to be equatable and takes a predicate as an
argument, see e.g. Shorthand to test if an object exists in an array for Swift?.
Swift older versions:
let elements = [1,2,3,4,5]
if contains(elements, 5) {
println("yes")
}
Swift - Check if a value belongs is in an array
First of all, array
s define with [Type]
like [User]
Second of all init
method calls as with (Arguments)
like User(name: ,age:)
And last but not least, don't forget the ',' between elements of the array.
So
struct User: Identifiable {
var id = UUID()
var name: String
var age: String
}
var array: [User] = [
User(name: "AZE", age: "10"),
User(name: "QSD", age: "37")
]
So now you can check your element inside with contains
like
array.contains(where: { user in user.name == "AZE" }) // returns `true` if it is
Tips
Try name array
s not array. Use plural names instead like users
To returtning the found one:
users.first(where: { user in user.name == "AZE" })
To summarizing it
users.first { $0.name == "AZE" }
How to update a specific property value of all elements in array using Swift
You just need to iterate your array indices
using forEach
method and use the array index to update its element property:
struct ViewHolder {
let name: String
let age: Int
var isMarried: Bool
}
var viewHolders: [ViewHolder] = [.init(name: "Steve Jobs", age: 56, isMarried: true),
.init(name: "Tim Cook", age: 59, isMarried: true)]
viewHolders.indices.forEach {
viewHolders[$0].isMarried = false
}
viewHolders // [{name "Steve Jobs", age 56, isMarried false}, {name "Tim Cook", age 59, isMarried false}]
You can also extend MutableCollection and create a mutating method to map a specific property of your collection elements as follow:
extension MutableCollection {
mutating func mapProperty<T>(_ keyPath: WritableKeyPath<Element, T>, _ value: T) {
indices.forEach { self[$0][keyPath: keyPath] = value }
}
}
Usage:
viewHolders.mapProperty(\.isMarried, false)
viewHolders // [{name "Steve Jobs", age 56, isMarried false}, {name "Tim Cook", age 59, isMarried false}]
Find an object in array?
FWIW, if you don't want to use custom function or extension, you can:
let array = [ .... ]
if let found = find(array.map({ $0.name }), "Foo") {
let obj = array[found]
}
This generates name
array first, then find
from it.
If you have huge array, you might want to do:
if let found = find(lazy(array).map({ $0.name }), "Foo") {
let obj = array[found]
}
or maybe:
if let found = find(lazy(array).map({ $0.name == "Foo" }), true) {
let obj = array[found]
}
Find Object with Property in Array
// this is not working - NSArray is not a subtype of Images- so what if there is only 1 possible result?
You have no way to prove at compile-time that there is only one possible result on an array. What you're actually asking for is the first matching result. The easiest (though not the fastest) is to just take the first element of the result of filter:
let imageObject = questionImageObjects.filter{ $0.imageUUID == imageUUID }.first
imageObject
will now be an optional of course, since it's possible that nothing matches.
If searching the whole array is time consuming, of course you can easily create a firstMatching
function that will return the (optional) first element matching the closure, but for short arrays this is fine and simple.
As charles notes, in Swift 3 this is built in:
questionImageObjects.first(where: { $0.imageUUID == imageUUID })
Related Topics
Convert Swift Array to Dictionary With Indexes
How to Access Nswindow from @Main App Using Only Swiftui
In Xcode 6.1. 'Uiimage' Does Not Have a Member Named 'Size' Error
Any Way to Iterate a Tuple in Swift
Using Foreach Loop with Binding Causes Index Out of Range When Array Shrinks (Swiftui)
Color Attribute Is Ignored in Nsattributedstring with Nslinkattributename
How to Check Is a String or Number
Create a Paginated PDF-MAC Os X
How to Convert Hex Number to Bin in Swift
Take a Snapshot of Current Screen with Metal in Swift
Swift 2.1 [Uint8] --Utf8--> String
Why Is There No Universal Base Class in Swift
Do Swift Inner Classes Have Access to Self of Outer Class
Is There a Prefix Header (Or Something with This Functionality) in Swift