I\'d like to implement a Swift method that takes in a certain class type, but only takes instances of those classes that comply to a specific protocol. For example, in Objec
Is swift you must use generics, in this way:
Given these example declarations of protocol, main class and subclass:
protocol ExampleProtocol {
func printTest() // classes that implements this protocol must have this method
}
// an empty test class
class ATestClass
{
}
// a child class that implements the protocol
class ATestClassChild : ATestClass, ExampleProtocol
{
func printTest()
{
println("hello")
}
}
Now, you want to define a method that takes an input parameters of type ATestClass (or a child) that conforms to the protocol ExampleProtocol. Write the method declaration like this:
func addFilter(newFilter: T)
{
println(newFilter)
}
Your method, redefined in swift, should be
func addFilter(newFilter:T!)
{
// ...
}
EDIT:
as your last comment, an example with generics on an Enum
enum OptionalValue {
case None
case Some(T)
}
var possibleInteger: OptionalValue = .None
possibleInteger = .Some(100)
Specialized with protocol conformance:
enum OptionalValue {
case None
case Some(T)
}
EDIT^2:
you can use generics even with instance variables:
Let's say you have a class and an instance variable, you want that this instance variable takes only values of the type ATestClass
and that conforms to ExampleProtocol
class GiveMeAGeneric
{
var aGenericVar : T?
}
Then instantiate it in this way:
var child = ATestClassChild()
let aGen = GiveMeAGeneric()
aGen.aGenericVar = child
If child
doesn't conform to the protocol ExampleProtocol
, it won't compile