Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 461 Vote(s) - 3.43 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to check if an element is in an array

#1
In Swift, how can I check if an element exists in an array? Xcode does not have any suggestions for `contain`, `include`, or `has`, and a quick search through the book turned up nothing. Any idea how to check for this? I know that there is a method `find` that returns the index number, but is there a method that returns a boolean like ruby's `#include?`?

Example of what I need:

var elements = [1,2,3,4,5]
if elements.contains(5) {
//do something
}
Reply

#2
Just in case anybody is trying to find if an `indexPath` is among the selected ones (like in a `UICollectionView` or `UITableView` `cellForItemAtIndexPath` functions):

var isSelectedItem = false
if let selectedIndexPaths = collectionView.indexPathsForSelectedItems() as? [NSIndexPath]{
if contains(selectedIndexPaths, indexPath) {
isSelectedItem = true
}
}


Reply

#3
The simplest way to accomplish this is to use filter on the array.

let result = elements.filter { $0==5 }

`result` will have the found element if it exists and will be empty if the element does not exist. So simply checking if `result` is empty will tell you whether the element exists in the array. I would use the following:

if result.isEmpty {
// element does not exist in array
} else {
// element exists
}

Reply

#4
I used filter.

let results = elements.filter { el in el == 5 }
if results.count > 0 {
// any matching items are in results
} else {
// not found
}

If you want, you can compress that to

if elements.filter({ el in el == 5 }).count > 0 {
}

Hope that helps.

---

**Update for Swift 2**

Hurray for default implementations!

if elements.contains(5) {
// any matching items are in results
} else {
// not found
}
Reply

#5
if user find particular array elements then use below code same as integer value.

var arrelemnts = ["sachin", "test", "test1", "test3"]

if arrelemnts.contains("test"){
print("found") }else{
print("not found") }
Reply

#6
As of Swift 2.1 NSArrays have `containsObject`that can be used like so:

if myArray.containsObject(objectImCheckingFor){
//myArray has the objectImCheckingFor
}

Reply

#7
Swift

If you are not using object then you can user this code for contains.

let elements = [ 10, 20, 30, 40, 50]

if elements.contains(50) {

print("true")

}

If you are using NSObject Class in swift. This variables is according to my requirement. you can modify for your requirement.

var cliectScreenList = [ATModelLeadInfo]()
var cliectScreenSelectedObject: ATModelLeadInfo!


This is for a same data type.

{ $0.user_id == cliectScreenSelectedObject.user_id }

If you want to AnyObject type.

{ "\($0.user_id)" == "\(cliectScreenSelectedObject.user_id)" }


Full condition

if cliectScreenSelected.contains( { $0.user_id == cliectScreenSelectedObject.user_id } ) == false {

cliectScreenSelected.append(cliectScreenSelectedObject)

print("Object Added")

} else {

print("Object already exists")

}
Reply

#8
_(Swift 3)_

### Check if an element exists in an array (fulfilling some criteria), _and if so, proceed working with the first such element_

If the intent is:

1. To check whether an element exist in an array (/fulfils some boolean criteria, not necessarily equality testing),
2. And if so, proceed and work with the first such element,

Then an alternative to [`contains(_:)`](

[To see links please register here]

) as blueprinted `Sequence` is to [`first(where:)`](

[To see links please register here]

) of `Sequence`:

let elements = [1, 2, 3, 4, 5]

if let firstSuchElement = elements.first(where: { $0 == 4 }) {
print(firstSuchElement) // 4
// ...
}

In this contrived example, its usage might seem silly, but it's very useful if querying arrays of non-fundamental element types for existence of any elements fulfilling some condition. E.g.

struct Person {
let age: Int
let name: String
init(_ age: Int, _ name: String) {
self.age = age
self.name = name
}
}

let persons = [Person(17, "Fred"), Person(16, "Susan"),
Person(19, "Hannah"), Person(18, "Sarah"),
Person(23, "Sam"), Person(18, "Jane")]

if let eligableDriver = persons.first(where: { $0.age >= 18 }) {
print("\(eligableDriver.name) can possibly drive the rental car in Sweden.")
// ...
} // Hannah can possibly drive the rental car in Sweden.

let daniel = Person(18, "Daniel")
if let sameAgeAsDaniel = persons.first(where: { $0.age == daniel.age }) {
print("\(sameAgeAsDaniel.name) is the same age as \(daniel.name).")
// ...
} // Sarah is the same age as Daniel.

Any chained operations using `.filter { ... some condition }.first` can favourably be replaced with `first(where:)`. The latter shows intent better, and have performance advantages over possible non-lazy appliances of `.filter`, as these will pass the full array prior to extracting the (possible) first element passing the filter.

---

### Check if an element exists in an array (fulfilling some criteria), _and if so, remove the first such element_

A comment below queries:

> How can I remove the `firstSuchElement` from the array?

A similar use case to the one above is to _remove_ the first element that fulfils a given predicate. To do so, the [`index(where:)`](

[To see links please register here]

) method of [`Collection`](

[To see links please register here]

) (which is readily available to array collection) may be used to find the index of the first element fulfilling the predicate, whereafter the index can be used with the [`remove(at:)`](

[To see links please register here]

) method of `Array` to (possible; given that it exists) remove that element.

var elements = ["a", "b", "c", "d", "e", "a", "b", "c"]

if let indexOfFirstSuchElement = elements.index(where: { $0 == "c" }) {
elements.remove(at: indexOfFirstSuchElement)
print(elements) // ["a", "b", "d", "e", "a", "b", "c"]
}

Or, if you'd like to remove the element from the array _and work with_, apply `Optional`:s [`map(_:)`](

[To see links please register here]

) method to conditionally (for `.some(...)` return from `index(where:)`) use the result from `index(where:)` to remove and capture the removed element from the array (within an optional binding clause).

var elements = ["a", "b", "c", "d", "e", "a", "b", "c"]

if let firstSuchElement = elements.index(where: { $0 == "c" })
.map({ elements.remove(at: $0) }) {

// if we enter here, the first such element have now been
// remove from the array
print(elements) // ["a", "b", "d", "e", "a", "b", "c"]

// and we may work with it
print(firstSuchElement) // c
}

Note that in the contrived example above the array members are simple value types (`String` instances), so using a predicate to find a given member is somewhat over-kill, as we might simply test for equality using the simpler `index(of:)` method as shown in [@DogCoffee's answer](

[To see links please register here]

). If applying the find-and-remove approach above to the `Person` example, however, using `index(where:)` with a predicate is appropriate (since we no longer test for equality but for fulfilling a supplied predicate).
Reply

#9
Here is my little extension I just wrote to check if my delegate array contains a delegate object or not (**Swift 2**). :) It Also works with value types like a charm.

extension Array
{
func containsObject(object: Any) -> Bool
{
if let anObject: AnyObject = object as? AnyObject
{
for obj in self
{
if let anObj: AnyObject = obj as? AnyObject
{
if anObj === anObject { return true }
}
}
}
return false
}
}

If you have an idea how to optimize this code, than just let me know.
Reply

#10
If you are checking if an instance of a **custom class or struct** is contained in an array, you'll need to implement the **Equatable** protocol before you can use .contains(myObject).

For example:

struct Cup: Equatable {
let filled:Bool
}

static func ==(lhs:Cup, rhs:Cup) -> Bool { // Implement Equatable
return lhs.filled == rhs.filled
}

then you can do:

cupArray.contains(myCup)

**Tip**: The == override should be at the global level, not within your class/struct

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through