Swift Generics issue
swift
Solution
With Swift, we'll need to think whether there's a function that can do the trick -- outside the methods of a class.
Just like in our case here:
contains(theArray, theItem)
You can try it in a playground:
let a = [1, 2, 3, 4, 5]
contains(a, 3)
contains(a, 6)
I discover a lot of these functions by cmd-clicking on a Swift symbol (example: Array) and then by looking around in that file (which seems to be the global file containing all declarations for Swift general classes and functions).
Here's a little extension that will add the "contains" method to all arrays:
extension Array {
func contains<T: Equatable>(item: T) -> Bool {
for i in self {
if item == (i as T) { return true }
}
return false
}
}
Problem
Right now I want to be able to see if an object is included inside an `Array` so: ``` func isIncluded<U:Comparable>(isIncluded : U) -> Bool { for item in self { if (item == isIncluded) { return true } } return false } ``` If you notice this function belongs to an `Array` extension. The problem is if add it to this: ``` extension Array{ } ``` I receive the following error: Could not find an overload for '==' that accepts the supplied arguments I understand that I could probably need to tell what kind of objects should be inside the `Array` like so: `T[] <T.GeneratorType.Element: Comparable>`. But it doesn't work as well: Braced block of statements is an unused closure Non-nominal type 'T[]' cannot be extended Expected '{' in extension