Swift Generics vs Any

♀尐吖头ヾ 提交于 2020-01-21 07:31:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!