问题
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
回答1:
Any
has nothing to do with generics, it is just a Swift type that can be used to represent an instance of any type at all, including function types (see the official documentation) hence you can cast an instance of any type to Any
. However, when using Any
with a specific type, you have to cast the Any
instance back to your actual type if you want to access functions/properties that are specific to the subclass.
When using generics there is no casting involved. Generics allow you to implement one function that works with all types that satisfy the type constraint (if you specify any), but when calling the function on a specific type, it will actually work with the specific type and not with non-specific type, like Any
.
In general, using generics for this kind of a problem is a better solution, since generics are strongly typed at compile time, while up/downcasting happens at runtime.
来源:https://stackoverflow.com/questions/45321753/swift-generics-vs-any