Golak Sarangi
Golak Sarangi

Reputation: 905

Extending the Set datatype in swift

I am a swift newbie. I have created a new method in the Set data structure for my code. This method inserts into set only if the value is not equal to a particular number.

extension Set {
    mutating func addExcludingCurrent(value: Int, currIndex: Int) {
        if value == currIndex {
            return
        } else {
            self.insert(value) // Error
        }
    }
}

Cannot invoke 'insert' with an argument list of type '(Int)' . How do I resolve it. Or else is there a better way to do this task ??

Upvotes: 1

Views: 1475

Answers (2)

Beraliv
Beraliv

Reputation: 564

Try this:

extension Set {
    mutating func addExcludingCurrent(value: Element, currIndex: SetIndex<Element>) {
        if value == currIndex {
            return
        } else {
            self.insert(value) // No more mistakes
        }
    }
}

In Swift Index is defined as follows:

public typealias Index = SetIndex<Element>

So you could write extension like this:

extension Set {
    mutating func addExcludingCurrent(value: Element, currIndex: Index) {
        if value == currIndex {
            return
        } else {
            self.insert(value) // No more mistakes
        }
    }
}

Upvotes: 0

Renzo
Renzo

Reputation: 27424

A Set is a struct whose AssociatedType is defined as Element. So you can extend it by inserting Elements, and not integers:

extension Set {
  mutating func addExcludingCurrent(value: Element, currIndex: Element) {
    if value == currIndex {
      return
    } else {
      self.insert(value)
    }
  }
}

var a = Set<Int>();
a.insert(3)
a.addExcludingCurrent(5,currIndex: 5)

Upvotes: 4

Related Questions