斯威夫特泛型vs任何 [英] Swift Generics vs Any

查看:122
本文介绍了斯威夫特泛型vs任何的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Apple网站上阅读了迅速的文档. 有一个函数swapTwoValues,可以交换两个给定的值

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
}

现在我想编写类似的函数,但我不想使用T泛型类型,而是要使用Any

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
}

调用此函数,我编写

var a = 5
var b = 9


swapTwoValues1(&a, &b)

swapTwoValues2(&a, &b)

我有两个问题.

1)为什么编译器会在第二个函数中出现此错误(不能将不可变值作为inout参数传递:从'Int'到'Any'的隐式转换需要临时使用)

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)泛型类型和Any之间有什么区别

2) What is the difference between Generic types and Any

推荐答案

Any与泛型无关,它只是一个Swift类型,可以用来表示任何类型的实例,包括函数类型(请参见官方文档),因此您可以将任何类型的实例转换为Any.但是,当将Any与特定类型一起使用时,如果要访问特定于子类的函数/属性,则必须将Any实例强制转换回实际类型.

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.

使用泛型时,不涉及任何强制转换.泛型允许您实现一个函数,该函数可用于满足类型约束的所有类型(如果您指定了任何类型),但是当在特定类型上调用该函数时,它将实际上仅适用于特定类型,而不适用于非特定类型,像Any.

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.

这篇关于斯威夫特泛型vs任何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆