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.

O.G.O
  • 149
  • 1
  • 9
  • well that is because your datasource is optional, if your datasource is nil, what do you expect to do? – Knight0fDragon Dec 21 '15 at 19:28
  • Well, KnightOfDragon, you right. changing optional to non-optional do the trick. Thank you – O.G.O Dec 21 '15 at 19:31
  • 1
    Possible duplicate of [How to check if an element is in an array](http://stackoverflow.com/questions/24102024/how-to-check-if-an-element-is-in-an-array) – Nikita Kurtin Dec 21 '15 at 19:31

2 Answers2

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
}
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • Wow! this really elegant solution. Gonna learn more about swift if statement – O.G.O Dec 21 '15 at 19:39
  • @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. – Luca Angeletti Dec 21 '15 at 20:43
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
    }
}
jkwuc89
  • 1,345
  • 14
  • 20
  • 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. – jkwuc89 Dec 21 '15 at 19:42
  • Yea, thank you for help, mate. appzYourLife was first so i should to accept his answer – O.G.O Dec 21 '15 at 19:45