Swift Generics vs Any -
i read swift documentation in apple site. there function swaptwovalues, swaps 2 given values
func swaptwovalues1<t>(_ a: inout t, _ b: inout t) { let temporarya = = b b = temporarya } now want write similar function instead of using t generic type want use
func swaptwovalues2(_ a: inout any, _ b: inout any) { let temporarya = = b b = temporarya } to call functions write
var = 5 var b = 9 swaptwovalues1(&a, &b) swaptwovalues2(&a, &b) i have 2 questions.
1) why compiler gives error second function (cannot pass immutable value inout argument: implicit conversion 'int' 'any' requires temporary)
2) difference between generic types , any
any has nothing generics, swift type can used represent instance of type @ all, including function types (see official documentation) hence can cast instance of type any. however, when using any specific type, have cast any instance actual type if want access functions/properties specific subclass.
when using generics there no casting involved. generics allow implement 1 function works types satisfy type constraint (if specify any), when calling function on specific type, work specific type , not non-specific type, any.
in general, using generics kind of problem better solution, since generics typed @ compile time, while up/downcasting happens @ runtime.
Comments
Post a Comment