Viktor Simkó Viktor Simkó - 5 months ago 17
Swift Question

Swift: Declaration in generic class

Let's say I have a generic class:

class SomeClass<Element> {
// What is the difference between this:
var array: [SomeClass]!

// and this declaration:
var array2: [SomeClass<Element>]!
}


What is the difference between those declarations?

Answer

A generic type cannot exist without its generic argument, therefore omitting the generic type means that you want the compiler to infer the type.

In this case the logical type to be inferred is Element.

Note that this works only because you have used SomeClass inside SomeClass declaration. It wouldn't work for a different generic class.

A similar inferring of generic arguments can be used in variable declarations:

let instance: SomeClass = SomeClass<Int>()
let array: Array = [1]