Generics - The Swift Programming Language (Swift 5.6)

Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner.

Generics are one of the most powerful features of Swift, and much of the Swift standard library is built with generic code. In fact, you’ve been using generics throughout the Language Guide, even if you didn’t realize it. For example, Swift’s Array and Dictionary types are both generic collections.

You can create an array that holds Int values, or an array that holds String values, or indeed an array for any other type that can be created in Swift.

Similarly, you can create a dictionary to store values of any specified type, and there are no limitations on what that type can be.

일반 코드를 사용하면 정의한 요구 사항에 따라 모든 Type에서 작동할 수 있는 유연하고 재사용 가능한 함수 및 Type을 작성할 수 있음

중복을 피하고 그 의도를 명확하고 추상적인 방식으로 표현하는 코드를 작성할 수 있음

The Problem That Generics Solve

Here’s a standard, nongeneric function called swapTwoInts(_:_:), which swaps two Int values:

func swapTwoInts(_ a: inout Int, _ b: inout Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

This function makes use of in-out parameters to swap the values of a and b, as described in In-Out Parameters.

The swapTwoInts(_:_:) function swaps the original value of b into a, and the original value of a into b. You can call this function to swap the values in two Int variables:

var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print("someInt is now \\(someInt), and anotherInt is now \\(anotherInt)")
// Prints "someInt is now 107, and anotherInt is now 3"