TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

What are generics?

Swift version: 5.6

Paul Hudson    @twostraws   

Generics are a way of making one data type act in a variety of ways depending on how it is created. You’ve already used them whether you realized or not: Swift has an Array type, but it is generic – it doesn’t contain any sort of specific data. Instead, you ask for arrays that hold specific kinds of data by using things like [String] to get a string array.

It’s not hard to create generics of your own, and to demonstrate that we’re going to create a simple Queue type. These are first-in, first-out data structures (FIFO), which means you add things to the back and remove them from the front – much like a real-life queue.

We want this queue to be generic, and in Swift you do that by writing the name of a generic placeholder inside angle brackets, like this: struct Queue<T> {. That T doesn’t mean anything special – it could have been R or Element – but T is commonly used.

Inside the queue we’re going to have an internal array tracking the items we’re storing, and we’ll write methods to add and remove items.

Here’s the complete Queue struct:

struct Queue<T> {
    private var internalArray = [T]()

    var count: Int {
        return internalArray.count

    mutating func add(_ item: T) {

    mutating func remove() -> T? {
        if internalArray.count > 0 {
            return internalArray.removeFirst()
        } else {
            return nil

You can now create a queue to store any object you want. For example, this create a queue of integers:

let queue = Queue<Int>()
Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 8.0 – learn more in my book Pro Swift

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.