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

#11
what about using a hash table for the job, like this?

first, creating a "hash map" generic function, extending the Sequence protocol.

extension Sequence where Element: Hashable {

func hashMap() -> [Element: Int] {
var dict: [Element: Int] = [:]
for (i, value) in self.enumerated() {
dict[value] = i
}
return dict
}
}

This extension will work as long as the items in the array conform to Hashable, like integers or strings, here is the usage...

let numbers = Array(0...50)
let hashMappedNumbers = numbers.hashMap()

let numToDetect = 35

let indexOfnumToDetect = hashMappedNumbers[numToDetect] // returns the index of the item and if all the elements in the array are different, it will work to get the index of the object!

print(indexOfnumToDetect) // prints 35

But for now, let's just focus in check if the element is in the array.

let numExists = indexOfnumToDetect != nil // if the key does not exist
means the number is not contained in the collection.

print(numExists) // prints true






Reply

#12
**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`][1] (for sequences of `Equatable` elements) and not a global method as in
earlier releases.

*Remarks:*

- This `contains()` method requires that the sequence elements
adopt the `Equatable` protocol, compare e.g. [Andrews's answer](

[To see links please register here]

).
- If the sequence elements are instances of a `NSObject` subclass
then you have to override `isEqual:`, see

[To see links please register here]

.
- 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.

[To see links please register here]

.

**Swift older versions:**

let elements = [1,2,3,4,5]
if contains(elements, 5) {
println("yes")
}


[1]:

[To see links please register here]

Reply

#13
### Array
let elements = [1, 2, 3, 4, 5, 5]

### Check elements presence
elements.contains(5) // true

### Get elements index
elements.firstIndex(of: 5) // 4
elements.firstIndex(of: 10) // nil

### Get element count
let results = elements.filter { element in element == 5 }
results.count // 2
Reply

#14
**Swift 4/5**

Another way to achieve this is with the filter function

var elements = [1,2,3,4,5]
if let object = elements.filter({ $0 == 5 }).first {
print("found")
} else {
print("not found")
}
Reply

#15
**Swift 4.2 +**
You can easily verify your instance is an array or not by the following function.

```swift
func verifyIsObjectOfAnArray<T>(_ object: T) -> Bool {
if let _ = object as? [T] {
return true
}

return false
}
```

Even you can access it as follows. You will receive `nil` if the object wouldn't be an array.

```swift
func verifyIsObjectOfAnArray<T>(_ object: T) -> [T]? {
if let array = object as? [T] {
return array
}

return nil
}
```
Reply

#16
For those who came here looking for a find and remove an object from an array:

**Swift 1**

if let index = find(itemList, item) {
itemList.removeAtIndex(index)
}

**Swift 2**

if let index = itemList.indexOf(item) {
itemList.removeAtIndex(index)
}

**Swift 3, 4**

if let index = itemList.index(of: item) {
itemList.remove(at: index)
}

**Swift 5.2**

if let index = itemList.firstIndex(of: item) {
itemList.remove(at: index)
}
Reply

#17
An array that contains a property that equals to
```
yourArray.contains(where: {$0.propertyToCheck == value })
```

Returns boolean.
Reply

#18
**Updated for Swift 2+**

Note that as of Swift 3 (or even 2), the extension below is no longer necessary as the global `contains` function has been made into a pair of extension method on `Array`, which allow you to do either of:

let a = [ 1, 2, 3, 4 ]

a.contains(2) // => true, only usable if Element : Equatable

a.contains { $0 < 1 } // => false

**Historical Answer for Swift 1:**

Use this extension: (updated to **Swift 5.2**)

extension Array {
func contains<T>(obj: T) -> Bool where T: Equatable {
return !self.filter({$0 as? T == obj}).isEmpty
}
}

Use as:

array.contains(1)

Reply

#19
You can add an extension for `Array` as such:

extension Array {
func contains<T>(_ object: T) -> Bool where T: Equatable {
!self.filter {$0 as? T == object }.isEmpty
}
}

This can be used as:

if myArray.contains(myItem) {
// code here
}
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

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