1

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.

3
  • well that is because your datasource is optional, if your datasource is nil, what do you expect to do? Commented Dec 21, 2015 at 19:28
  • Well, KnightOfDragon, you right. changing optional to non-optional do the trick. Thank you Commented Dec 21, 2015 at 19:31
  • 1
    Possible duplicate of How to check if an element is in an array Commented Dec 21, 2015 at 19:31

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Wow! this really elegant solution. Gonna learn more about swift if statement
@O.G.O Good! A suggestion for the future. Try to avoid the force unwrap (I mean this !). It's risky and often there is a safer way to unwrap an optional.
0

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

2 Comments

It looks like my proposed solution is similar to one proposed by appzYourLife above. Concept is generally the same. Unwrap the optionals safely and then, use them.
Yea, thank you for help, mate. appzYourLife was first so i should to accept his answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.