Generics apply to structures.
Consider the following implementation of a queue using a structure:
struct MyGenericQueue < T > { var elements = [T ]() var startIndex = 0 mutating func queue(item: T ) { elements.append(item) } mutating func dequeue() -> T! { if elements.isEmpty { return nil } else { return elements.removeAtIndex (0) } } }
You can now use the MyGenericQueue structure for any specified data type:
struct MyGenericQueue < T > { var elements = [T ]() var startIndex = 0 mutating func queue(item: T ) { elements.append(item)// w w w . j ava2 s .c om } mutating func dequeue() -> T! { if elements.isEmpty { return nil } else { return elements.removeAtIndex (0) } } } var myGenericQueue = MyGenericQueue<String>() myGenericQueue.queue(item:"Hello") myGenericQueue.queue(item:"Swift") print(myGenericQueue.dequeue()) //Hello print(myGenericQueue.dequeue()) //Swift print(myGenericQueue.dequeue()) //nil