简体   繁体   English

swift中任何类型和泛型类型之间的区别

[英]The difference between an any type and a generic type in swift

What is the difference between an any type and generic type in swift? swift中的任意类型和泛型之间有什么区别?

Any Type Example: 任何类型的示例:

let swiftInt: Int = 1
let swiftString: String = "miao"

var array: [Any] = []
array.append(swiftInt)
array.append(swiftString)

Generic Type Example: 通用类型示例:

func duplicate<T>(item: T, numberOfTimes n: Int) -> [T] {
  var buffer : [T] = []
  for _ in 0 ..< n {
    buffer.append(item)
  }
  return buffer
}

Is this a matter of preference because both appear to solve the same problem by being able to substitute the desired type. 这是优先问题吗,因为两者似乎都可以通过替换所需的类型来解决相同的问题。

I'm not going to explain generics in details and i'll just point out the essential differences. 我不会详细解释泛型,而只是指出基本区别。

In the first example, you'll be able to append any type in that array, without being able to restrict beforehand your array to a specific type and to leverage compile time checks to guarantee that the array will not contain extraneous types. 在第一个示例中,您将能够在该数组中附加任何类型,而无需事先将您的数组限制为特定类型,并能够利用编译时检查来确保该数组不包含无关类型。 Not much to see in that example. 在该示例中看不到太多。

The second example contains instead a generic function that provides all of the above functionalities, consistency checks on the content of the array will come for free and if you want you'll also be able to specify additional characteristics of that generic type T , like requesting that it implements a specific protocol (eg limit duplicate() to object that implement Comparable or Equatable ). 第二个示例包含提供上述所有功能的泛型函数,将免费提供对数组内容的一致性检查,并且如果您希望,还可以指定该泛型T其他特征,例如请求它实现了一个特定的协议(例如,将Equatable duplicate()限制为实现ComparableEquatable对象)。

But that is just a simple example of a generic function, you can also have parametrized classes (what you'll use the most) and there are a lot of additional functionalities. 但这只是通用函数的简单示例,您还可以具有参数化的类(您将最常使用的类),并且还有很多其他功能。

Never use Any as a poor-man generics, real generics are way more flexible, add useful checks and make more explicit your intentions, with minimal additional effort required to implement them. 切勿将Any用作穷人通用名,真正的通用名会更灵活,添加有用的检查并更明确地表明您的意图,而只需花费很少的精力即可实现它们。

Any means "I don't want any type checking and I won't be able to call type-specific methods without casting" Any意思是“我不需要任何类型检查,并且如果不进行强制转换,将无法调用特定于类型的方法”

For example, try to call: 例如,尝试调用:

var array: [Any] = [1, 2]
var sum = array[0] + array[1] // you cannot do this! you have to cast to Int first

A generic type is a placeholder for a type. 泛型类型是类型的占位符。 When used, a concrete type is used instead of it (eg an Int or a String ). 使用时,将使用具体类型代替它(例如, IntString )。

In short, never use Any . 简而言之,永远不要使用Any There are very very few specific situations when Any is what you want to use. 当您要使用Any时,很少有特定情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM