Categories
functional-programming ios swift

Difference between Generics and AnyObject in Swift

Consider this myFilter function that takes in a generic argument and filters the array based on the predicate. This is same as the filter() function provided by Swift.

func myFilter<T>(source: [T], predicate:(T) -> Bool) -> [T] {
var result = [T]()
for i in source {
if predicate(i) {
result.append(i)
}
}
return result
}

How is this different from,

func myFilter(source: [AnyObject], predicate:(AnyObject) -> Bool) -> [AnyObject] {
var result = [AnyObject]()
for i in source {
if predicate(i) {
result.append(i)
}
}
return result
}

Aren’t we achieving the point of generics even in the latter example?