Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic collection of X in Swift?

I'm trying to formulate a delegate protocol that can take in a collection of objects of type X. The same method of this protocol should be able to take instances of:

  • Set<X>
  • Array<X>
  • LazyMapCollection<Dictionary<_, X>, X> (this last one is from Dictionary.values)

The question is, how to declare the protocol method?

The following are some candidate method declarations that didn't work quite right:

public protocol BlahDelegate : NSObjectProtocol {
    // won't compile; 'cannot specialize generic type "Sequence"'
    func blah(_ sender: Blah,foundStuff stuff: Sequence<Stuff>)

    // won't compile; 'cannot specialize generic type "Collection"'
    func blah(_ sender: Blah,foundStuff stuff: Collection<Stuff>)

    // this can't take in Set<Stuff> nor LazyMapCollection<Dictionary<_, Stuff>, Stuff>
    func blah(_ sender: Blah,foundStuff stuff: Array<Stuff>)

    // this can't take in Array<Stuff> nor LazyMapCollection<Dictionary<_, Stuff>, Stuff>
    func blah(_ sender: Blah,foundStuff stuff: Set<Stuff>)
}

PS: This is for Swift 3.

like image 978
adib Avatar asked Oct 25 '25 04:10

adib


1 Answers

You will need to make the method itself generic, and use the type parameter as the type of the "normal" parameter. You can then also restrict associated types of that first type. So for example:

func blah<T>(stuff: T) where T : Sequence, T.Iterator.Element : Stuff

means that stuff must be a Sequence whose element type is something that conforms to or inherits from Stuff.

like image 113
jscs Avatar answered Oct 26 '25 22:10

jscs