What does <> (angle brackets) do on class names in swift?
10,527
It makes the class generic. The Swift standard library doesn't have a lot of examples of generic classes, but it has some very well-known generic structs and enums:
public struct Array<Element> : CollectionType, MutableCollectionType, _DestructorSafeContainer
public struct Dictionary<Key : Hashable, Value> : CollectionType, DictionaryLiteralConvertible
public enum Optional<Wrapped> : _Reflectable, NilLiteralConvertible
Read more about generics under “Generics” in The Swift Programming Language.
Related videos on Youtube
Author by
Chowdhury Md Rajib Sarwar
Updated on September 16, 2022Comments
-
Chowdhury Md Rajib Sarwar over 1 year
In a class declaration what is the use of <> angle brackets and the parameters declared inside in swift? Like as:
public class ClassName<T: Comparable> { }
-
Chowdhury Md Rajib Sarwar over 8 yearsWhy do we need to use Generic? I I want to transfer an array from one class to another than is generic is useful? How?
-
rob mayoff over 8 yearsThat question is too broad. You need to read the section of the Swift book that I referred to in my answer, or be specific about what “one class” is and what “another” is and what is in “an array”.
-
Rob over 8 yearsAyon, no, generics are not for "converting", but rather a way of declaring a class or struct as being useful for a variety of types, but doing so in a strongly-typed way. Your question about arrays is ironic, because Swift arrays are generics (e.g. an instance of an array can be an array of a particular type and only that type, but all array instances enjoy the same set of methods, properties, etc.).