Constrained genericity: Difference between revisions

added swift
(added swift)
Line 821:
val foodBox = new FoodBox(List(new Fish("salmon")))</lang>
A more extensive discussion on genericity in Scala and some of the constrains that can be imposed can be found on [[Parametric Polymorphism]].
 
=={{header|Swift}}==
Here we make <code>Eatable</code> a protocol, with an <code>eat</code> method. Types which are Eatable would have to conform to the <code>Eatable</code> protocol and provide an <code>eat</code> method.
<lang swift>protocol Eatable {
func eat()
}</lang>
Type constraints in type parameters can be made via the <code>:</code> syntax, indicating in this case that the type argument must be a type that is a subtype of <code>Eatable</code>.
<lang swift>struct FoodBox<T: Eatable> {
var food: [T]
}</lang>
Similarly a generic function or method can constrain its type parameters
<lang swift>func foo<T: Eatable>(x: T) { }
// although in this case this is no more useful than just "func foo(x: Eatable)"</lang>
 
<!-- Place omit from templates below here -->
Anonymous user