Quick Conformance to Standard Protocol

I am trying to extend the Swift class Arraywith the following function:

func containsObjectIdenticalTo(obj: T) -> Bool {
    // objectPassingTest returns the first object passing the test
    return objectPassingTest { x in x == obj }
}

Apparently, this will not compile, since the compiler does not yet know if it is ==implemented for the type T. Then I change the code to

func containsObjectIdenticalTo(obj: T) -> Bool {
    return objectPassingTest {
        x in
        assert(x is Equatable && obj is Equatable)
        return (x as Equatable) == (obj as Equatable)
    } != nil
}

This also does not work, since Equatableit is impossible to verify compliance with (since Equatableit was not determined using @obj) !

Any thoughts on this? It would be nice if there was some way to directly state if it Tmatches Equatable, but I have not read it anywhere. Swift seems less dynamic than Obj-C in these materials.

UPDATE: I tried this sentence, and it does not work (I don’t know exactly why <T: Equatable>, it compiles).

func containsObjectIdenticalTo<T: Equatable>(obj: T) -> Bool {
    var x = self[0]
    var y = self[0]
    return x == y // Error here
}
+4
4

, T :

func containsObjectIdenticalTo<T: Equatable>(obj: T) -> Bool {/*...*/}
+4

:

func containsObjectIdenticalTo<T : Equatable>(obj: T) -> Bool {
 ... etc ...
}
+1

In the end, I turned to this decision

func containsObjectIdenticalTo<U: Equatable>(obj: U) -> Bool {
    return objectPassingTest({
        x in
        return x as U == obj
    }) != nil
}

It may not be the best (i.e. safe ). But it works great.

+1
source

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

+1
source

Source: https://habr.com/ru/post/1544249/


All Articles