Sunday, 15 February 2015

ios8 - Diffrence between Function and Generic Function in swift -



ios8 - Diffrence between Function and Generic Function in swift -

i want know difference between function , generic function in swift.following function , generic function doing same..can tell me exact utilize of generic functions ?

func simplemin<t: comparable>(x: t, y: t) -> t { //generic functions if x < y { homecoming y } homecoming x } func samplemin(x:anyobject,y:anyobject)->anyobject{ //function if x.integervalue < y.integervalue { homecoming y } homecoming x }

generic functions allow utilize type safety of swift on both parameters , result of function write safer, cleaner code. example, first function requires both parameters passed in of same type, , guarantees homecoming value of same type:

let minint: int = simplemin(5, 12) allow mindouble: double = simplemin(5.0, 12.0)

whereas sec function makes no such requirements , no such guarantee:

let minone: anyobject = samplemin(5, 12.0) // minone anyobject holding int allow mintwo: anyobject = samplemin(5.0, 12) // mintwo anyobject holding double allow minthree: anyobject = samplemin("five", true) // supposed happen here, exactly?

with these anyobject results need checks create sure understand function returned, since anyobject (obviously) much less specific original parameters.

moreover, generic functions allow set constraints on parameters accept, can create sure function called arguments create sense. first function requires parameters conform comparable protocol, meaning can't phone call 2 random objects. compiler allow me phone call sec function 2 instances of uiview, example, , there won't problem until crash when code executed.

understanding protocols of import part of using generics. protocol defines specific functionality useful across whole range of classes, , leaves implementation of functionality classes themselves. comparable protocol above 1 example; here's definition:

protocol comparable : equatable { func <=(lhs: self, rhs: self) -> bool func >=(lhs: self, rhs: self) -> bool func >(lhs: self, rhs: self) -> bool }

this saying object "conforms to" comparable protocol going have definitions using <=, >=, , > operators -- is, you'd able write if > b 2 objects both comparable.

more reading: the swift programming language: generics generic programming - wikipedia

generics have long been feature of c# , java, among other languages, may find more resources help understand benefits , how utilize them in documentation.

swift ios8 xcode6

No comments:

Post a Comment