i want to know the difference between the Function and Generic function in swift.Following Function and Generic function is doing same..can anyone tell me the exact use of Generic functions ?
func simpleMin<T: Comparable>(x: T, y: T) -> T { //Generic functions
if x < y {
return y
}
return x
}
func sampleMin(x:AnyObject,y:AnyObject)->AnyObject{ //Function
if x.integerValue < y.integerValue {
return y
}
return x
}
Generic function is more descriptive and type Safe: Example : If it is generic function calling the function with wrong type results in compile time error i.e
simpleMin(100, y: 200) // Valid as type is same as T
simpleMin(someOtherTypedObject, y: 100.0) // Compile time error due to mismatch in type
Generic type can have Type constraints which specify that a type parameter must inherit from a specific class, or conform to a particular protocol or protocol composition. But its not possible to specify type constraints to AnyObjectType
i.e the bellow declaration gives compile time error
In Second function definition you can't make sure that variables passed are comparable.
Generic functions let you use the type safety of Swift on both the parameters and the result of the function to write safer, cleaner code. For example, your first function requires that both parameters passed in be of the same type, and guarantees a return value of that same type:
whereas your second function makes no such requirements and no such guarantee:
With these
AnyObject
results I would need to do extra checks to make sure I understand what the function returned, sinceAnyObject
is (obviously) much less specific than my original parameters.Moreover, generic functions allow you to put constraints on the parameters they accept, so you can make sure that the function is called only with arguments that make sense. Your first function requires that the parameters conform to the
Comparable
protocol, meaning that I can't just call it with two random objects. The compiler will let me call your second function with two instances ofUIView
, for example, and there won't be any problem until the crash when that code is executed.Understanding protocols is an important part of using generics. A protocol defines some specific functionality that would be useful across a whole range of classes, and leaves the implementation of that functionality up to the classes themselves. The
Comparable
protocol above is one example; here's the definition:This is saying that any object that "conforms to" the
Comparable
protocol is going to have definitions for using the<=
,>=
, and>
operators -- that is, you'd be able to writeif a > b
for any two objects that are bothComparable
.More reading:
The Swift Programming Language: Generics
Generic Programming - Wikipedia
Generics have long been a feature of C# and Java, among other languages, so you may find more resources to help you understand their benefits and how to use them in their documentation.