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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…