Array Element Checking in Swift

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 the Equatable protocol, compare e.g. Andrews's answer.
  • If the sequence elements are instances of a NSObject subclass
    then you have to override isEqual:, 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")
}

Check if array contains element in Swift 4

Thanks to your comments made me check the declaration of the array and the problem was that was declared as [Any] after I get it's value from the UserDefaults. I have checked and found the solution on How do I save an Int array in Swift using NSUserDefaults?

// old declaration
let categories = userDefaults.array(forKey:"categories") ?? [Int]()

// new correct declaration
var categories = [Int]()
if let temp = userDefaults.array(forKey:"categories") as? [Int] {
categories = temp
}

Swift Array - Check if an index exists

An elegant way in Swift:

let isIndexValid = array.indices.contains(index)

Swift - Check if a value belongs is in an array

First of all, arrays 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 arrays 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" } 

In Swift, How to check if the first element of an Array is equal to a list of values?

Any time you have many of something and you want to know whether your target is among them, the search is far more efficient if you use a set.

let lettersToLookFor = Set("AEIOU")

You also have to be careful in this example to specify whether we are talking here about characters or strings. I have chosen to let lettersToLookFor be a set of characters.

Now the question is easy to answer using contains:

let listOfLetters : [Character] = ["A","C","D","E","L"]
let ok = lettersToLookFor.contains(listOfLetters[0]) // true

Checking all elements in an array in Swift against each other

Not sure about the circle's array but to check each element of the circle's array against each other you can use a nested loop. The below code might help you.

for i in 0..<circles.count{
circles[i].center = getRandomPoint()
for j in 0..<circles.count{
if(i != j){
let comparingCentre = circles[j].center
let dist = distance(comparingCentre, circles[i].center)
if dist <= 50 {

var newCenter = circles[i].center
var centersVector = CGVector(dx: newCenter.x - comparingCentre.x, dy: newCenter.y - comparingCentre.y)

centersVector.dx *= 51 / dist
centersVector.dy *= 51 / dist
newCenter.x = comparingCentre.x + centersVector.dx
newCenter.y = comparingCentre.y + centersVector.dy
circles[i].center = newCenter
}
}
}
}

Swift - Check if array contains element with property

Yes,

if things.contains(where: { $0.someProperty == "nameToMatch" }) {
// found
} else {
// not
}

Checking if an array contains a string

theres also anomalies like when I passed in "https://twitter.com"
it'll return true.

Whether the version of Swift is 3 or 4, based on your code snippet you should get the same true result! Why?

because the logic of contains(where:) of doing the comparison is related to the logic of the equality of the given elements, i,e you cannot use contains with array of non-equatable elements. To make it more clear:

"https://apple.com" <= "https://twitter.com"
"https://facebook.com" <= "https://twitter.com"
"https://stackoverflow.com" <= "https://twitter.com"

the result would be true for all statements ('t' character is greater than 'a', 'f' and 's').

Thus:

"https://zwebsite" <= "https://twitter.com"

would returns false ('t' is less than 'z').

However, to get the expected result, you could implement your function like this:

func isValid(_ item: String)  -> Bool {

let whitelist = ["https://apple.com","https://facebook.com","https://stackoverflow.com"]

return whitelist.contains { $0 == item }
}

Or for even a shorter contains:

return whitelist.contains(item)

Which leads to let

isValid("https://twitter.com")

to returns false.

Check if an array contains elements of another array in swift

You can simply create a set from your first collection and get its intersection with the other collection:

let array1 = ["user1", "user2", "user3", "user4"]
let array2 = ["user3", "user5", "user7", "user9", "user4"]
let intersection = Array(Set(array1).intersection(array2)) // ["user4", "user3"]

Note that the order of the resulting collection is unpredictable. If you would like to preserve the order of the first collection you can create a set of the second collection and filter the elements that cannot be inserted to it:

var set = Set(array2)
let intersection = array1.filter { !set.insert($0).inserted } // ["user3", "user4"]

You can also create your own intersection method on RangeReplaceableCollection:

extension RangeReplaceableCollection {
func intersection<S: Sequence>(_ sequence: S) -> Self where S.Element == Element, Element: Hashable {
var set = Set(sequence)
return filter { !set.insert($0).inserted }
}
}

Usage:

let intersection = array1.intersection(array2)  // ["user3", "user4"]


Related Topics



Leave a reply



Submit