-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?
    – Alexander
    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
    – swiftPunk
    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.
    – Alexander
    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
    – swiftPunk
    Commented Aug 2, 2022 at 21:04
  • 2

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!"
    )
  }
}
2
  • 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?
    – swiftPunk
    Commented Aug 2, 2022 at 20:34
  • 1
    It's an unordered sequence of key-value pairs, yes. Those cannot be Equatable because they are tuples.
    – user652038
    Commented Aug 2, 2022 at 21:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.