I am trying to extend Swift's Array
class with the following func:
func containsObjectIdenticalTo(obj: T) -> Bool {
// objectPassingTest returns the first object passing the test
return objectPassingTest { x in x == obj }
}
Apparently, this won't compile as the compiler doesn't know yet if ==
is implemented for type T
. I then change the code to this
func containsObjectIdenticalTo(obj: T) -> Bool {
return objectPassingTest {
x in
assert(x is Equatable && obj is Equatable)
return (x as Equatable) == (obj as Equatable)
} != nil
}
Which doesn't work either, since conformance against Equatable
can't be checked (because Equatable
wasn't defined with @obj
) !
Any thoughts on this? Would be nice if there's some way to assert directly if T
conforms to Equatable
, but I haven't read that anywhere. Swift seems to be less dynamic than Obj-C in these stuffs.
UPDATE:
Tried this suggestion and it doesn't work (don't know exactly what <T: Equatable>
is for, tho it does compile).
func containsObjectIdenticalTo<T: Equatable>(obj: T) -> Bool {
var x = self[0]
var y = self[0]
return x == y // Error here
}
The short answer is that we can't. Each conforming type can be Equatable (in fact both our concrete types are) but we don't have a way of checking equality at the level of the protocol since the protocol does not declare any properties.
Overview. Types that conform to the Equatable protocol can be compared for equality using the equal-to operator ( == ) or inequality using the not-equal-to operator ( != ). Most basic types in the Swift standard library conform to Equatable .
In Swift, an Equatable is a protocol that allows two objects to be compared using the == operator. The hashValue is used to compare two instances. To use the hashValue , we first have to conform (associate) the type (struct, class, etc) to Hashable property.
Caveats while using Equatable with NSObject It is possible for that specific construct to conform to Equatable protocol and implement the required method.
Specify that T must be equatable in the Method's signature:
func containsObjectIdenticalTo<T: Equatable>(obj: T) -> Bool {/*...*/}
i got this from ExSwift : https://github.com/pNre/ExSwift
func contains <T: Equatable> (items: T...) -> Bool {
return items.all { self.indexOf($0) >= 0 }
}
func indexOf <U: Equatable> (item: U) -> Int? {
if item is Element {
if let found = find(reinterpretCast(self) as Array<U>, item) {
return found
}
return nil
}
return nil
}
func all (call: (Element) -> Bool) -> Bool {
for item in self {
if !call(item) {
return false
}
}
return true
}
maybe you can try it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With