user6510422 user6510422 - 1 year ago 61
Swift Question

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?

Any Type Example:

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

var array: [Any] = []

Generic Type Example:

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

Is this a matter of preference because both appear to solve the same problem by being able to substitute the desired type.

Answer Source

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 (e.g. limit duplicate() to object that implement Comparable or Equatable).

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download