2

Is it possible to construct a collection (array, dictionary, set) type checks values against both a class and a protocol? Given:

class Piece {
  var name: String?
}

protocol Jump {
  func jump() { ... }
}

protocol Move {
  func move() { ... }
}

Allows:

var pieces: [Piece]?

Or:

 var moves: [Move]?
 var jumps: [Jump]?

Or:

 var movenjump: [protocol <Move,Jump>]

But, I'm not sure how to restrict a collection to instances of Piece that Move and Jump.

Kevin Sylvestre
  • 37,288
  • 33
  • 152
  • 232
  • You should get some ideas from this post: http://stackoverflow.com/questions/30398786/check-if-optional-protocol-method-is-implemented-in-swift, or you can just create *delegates* for each protocol and check whether they're nil or not. – Kyle Emmanuel Aug 13 '15 at 23:41
  • 1
    I'd look for generics with a where clause: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GenericParametersAndArguments.html something like let movenjump: Array – Gerd Castan Aug 14 '15 at 00:17

1 Answers1

0

The short answer is no. To date, Swift only allow collections for either a single Class type or protocol types (single protocol or multiple protocols). But there are ways you can workaround this.

  1. The best approach is if Piece is your code, try to make it a protocol. Then you can declare array for example: let anArray: [protocol<Piece, Move, Jump>].

  2. If you don't have access to the source code of Piece, try to generify the surrounding class which needs to declare the collection. This way, you can use where clause to constrain the generic type to anything you like:

    class MyClass<T where T: Piece, T: Move, T: Jump> {
        var myCollection: [T]?
    }
    
Fujia
  • 1,232
  • 9
  • 14