4

I have two protocols Valid and Resetable and an array of inputViews that is of type [Valid]. That all works fine. So now I've got my Resetable protocol:

protocol Resetable: class {
    func reset()
}

Now, everything inside of inputViews also conforms to the Resetable protocol, so what I want to do is basically loop through and call reset() on each member. If I do this then it will work:

    for input in inputViews {
        (input as! Resetable).reset()
    }

But i've extended Array with the following:

extension Array where Element:Resetable {
    func resetAll() {
        forEach({ $0.reset() })
    }
}

So what I really want to be able to do is downcast inputViews entirely and call resetAll().

I tried:

    let resetableViews = inputViews.map({ $0 as! Resetable })
    resetableViews.resetAll()

But it says Using Resetable as a concrete type conforming to Resetable is not supported

How can I achieve this by using resetAll()?

Peter Foti
  • 5,526
  • 6
  • 34
  • 47
  • Resettable is actually spelled with two t's, like forgettable/regrettable, but unlike deletable/depletable, or marketable/pocketable. –  Nov 06 '15 at 16:41
  • 2
    Compare http://stackoverflow.com/questions/33112559/protocol-doesnt-conform-to-itself. – Martin R Nov 06 '15 at 17:11

1 Answers1

0

I hope I have understood the question / specs. Freely taking from Rob Napier, how about:

protocol Resettable {
    func reset() -> Resettable
}

struct ResettableArray {
    var array: [Resettable]
    init(_ array:[Resettable]) { self.array = array }
    func resetAll() -> [Resettable] {
        return array.map( { $0.reset() } )
    }
}

class dummy: Resettable {
    func reset() -> Resettable {
        print("Reset one element")
        return self
    }
}

let resettableDummy = ResettableArray([dummy(), dummy()])
resettableDummy.resetAll()
Eppilo
  • 763
  • 6
  • 19