xcode - Swift: filter protocol array by comparing types -
(first post)
usually im able find answers here or elsewhere no luck time =(
question: in swift, how filter array of protocol type implementing type supplied function parameter?
protocol aprotocol { var number:int { set } } class aclass: aprotocol { var number = 1 } class anotherclass: aprotocol { var number = 1 } var array:[aprotocol] = [ aclass(), anotherclass(), aclass() ] func foo (parameter:aprotocol) -> int { return array.filter({ /* p in p.self == parameter.self */ }).count } var bar:aprotocol = // aclass() or anotherclass() var result:int = foo(bar) // should return 2 or 1, depending on bar type
maybe not right approach @ all?
thanks!
here think want:
return array.filter { (element: aprotocol) -> bool in element.dynamictype == parameter.dynamictype }.count
but recommend this, same, without useless instance of aclass()
passed in answer on top. way faster:
func foo <t: aprotocol>(type: t.type) -> int { return array.filter { (element: aprotocol) -> bool in element.dynamictype == type }.count } var result:int = foo(aclass)
the dynamictype
return type of instance
Comments
Post a Comment