O.G.O
O.G.O

Reputation: 159

How to properly check if array contains an element inside if statement

I have this line of code:

   if ((self.datasource?.contains((self.textField?.text)!)) != nil) {
            if let _ = self.placeHolderWhileSelecting {
               // some code
            }

Is there more clear way to check if the element contains in array? I have Bool returned by contains function, I dont want to check if this Bool is nil

Edit: the solution is to change array to non-optional type.

Upvotes: 1

Views: 140

Answers (2)

Luca Angeletti
Luca Angeletti

Reputation: 59496

You can use the if let where construct. This code prevent crashes if self.datasource or self.textField are nil

if let
    list = self.datasource,
    elm = self.textField?.text,
    _ = self.placeHolderWhileSelecting
    where list.contains(elm) {
        // your code
}

Upvotes: 1

jkwuc89
jkwuc89

Reputation: 1415

Another possible solution, using optional chaining to get to self.textField.text and assuming datasource remains optional.

if let unwrappedArray = self.datasource, let unwrappedString = self.textField?.text {
    if unwrappedArray.contains(unwrappedString) {
        // Some code
    }
}

Upvotes: 0

Related Questions