-2

I am using contains function in a function which array is a string array, like this:

func addArrayCheck(array: Array<String>, value: String) {
    if (array.contains(value)) {
        print("Element exists!")
    }
    else {
        print("Element does not exists!")
    }
}

Then I tried to make an extension, but Xcode complain about this:

Missing argument label 'where:' in call

extension Array {
    func addArrayCheck(value: Self.Element) {
        if self.contains(value) {
            print("Element exists!")
        }
        else {
            print("Element does not exists!")
        }
    }
}

Why I cannot use contains like I used in function in generic form? and how can I solve the issue?

8
  • Are you planning to implement addArrayCheck to add elements, only if they're already not present in the array? Commented Aug 2, 2022 at 15:28
  • Yes, that is correct, I do not want have same value in array, do you mean there is better way? @Alexander Commented Aug 2, 2022 at 20:35
  • 1
    Yeah, you should probably avoid that, because contains(_:) has linear (O(array.count)) time complexity. If you're sure your array won't get long, it's fine, but I'd generally suggest just using a Set, or an OrderedSet if you need to preserve element order. Commented Aug 2, 2022 at 21:00
  • I never saw OrderedCollections or OrderedSet before! Is it basically a set that we make an order at end? when we done with adding elements? @Alexander Commented Aug 2, 2022 at 21:04
  • 2
    @ioscoder Check this related post How to implement a Mutable Ordered Set generic type formerly known as NSMutableOrderedSet in native Swift? Commented Aug 2, 2022 at 21:28

1 Answer 1

4

That contains overload only works when your elements are Equatable.

extension Sequence where Element: Equatable {
  func addCheck(value: Element) {
    print(
      contains(value)
        ? "Element exists!"
        : "Element does not exist!"
    )
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I see you updated my approach with using Sequence, thanks, but Dictionary is not a Sequence?! your code works on array and set, but not in Dictionary, I think Dictionary is a Sequence, right?
It's an unordered sequence of key-value pairs, yes. Those cannot be Equatable because they are tuples.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.