I read swift documentation in apple site. There is a function swapTwoValues, which swaps two any given values
func swapTwoValues1<T>(_ a: inout T, _ b: inout T) {
let temporaryA = a
a = b
b = temporaryA
}
Now I want to write similar function but instead of using T generic type I want to use Any
func swapTwoValues2(_ a: inout Any, _ b: inout Any) {
let temporaryA = a
a = b
b = temporaryA
}
to call this functions I write
var a = 5
var b = 9
swapTwoValues1(&a, &b)
swapTwoValues2(&a, &b)
I have two questions.
1) Why the compiler gives this error for second function (Cannot pass immutable value as inout argument: implicit conversion from 'Int' to 'Any' requires a temporary)
2) What is the difference between Generic types and Any
Any
. The compiler cannot know at compile time what concrete type is actually contained withina
andb
in yourAny
implementation. – StipeString
and anInt
? How would you imagine a swap to work in this case? – LactoflavinAny
(as the only use case for these are when both arguments actually "wraps" the same concrete types: but this case if fully covered by the generic approach). – StipeInt
but want to pass it to a method as anAny
pointer which looses type information - the only reason you would want to pass a pointer / inout is that you want to set its value from inside the function. And that is not possible for the reason(s) given already. – Lactoflavin