Swift Generic(제네릭)이란

‍deprecated·2021년 8월 11일
0

Generic

Generic(제네릭) 모든 타입에서 동작할 수 있는 유연하고 재사용 가능한 함수와 타입을 작성할 수 있게 해줍니다. 이를 통해 중복을 피하고, 의도를 보다 깔끔하게, 추상적으로 코드를 작성할 수 있습니다.

실제로 스위프트의 standard library는 제네릭 코드로 작성되었습니다. Array, Dictionary 역시 제네릭 컬렉션입니다. 우리는 Int값을 가지는 배열도 만들 수 있고, String 값을 가지는 배열도 만들 수 있습니다.

제네릭이 해결하는 문제

다음 2개의 Int값을 바꾸는 swapTwoInts 라는 '함수'를 살펴볼게요.

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

inout 파라미터를 사용하여 a와 b의 값을 바꿉니다.
실제로 호출은 아래와 같이 하면 되겠네요.

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"

근데 Int 뿐 아니라 String, Double도 값을 바꾸려면 함수를 새롭게 만들어줘야 하는 단점이 있습니다. 아래와 같이요.

func swapTwoStrings(_ a: inout String, _ b: inout String) {
    let temporaryA = a
    a = b
    b = temporaryA
}

func swapTwoDoubles(_ a: inout Double, _ b: inout Double) {
    let temporaryA = a
    a = b
    b = temporaryA
}

body는 동일한데 type만 다르다고 함수를 새롭게 작성하는 것이 상당히 많이 번거롭습니다.
이를 단일 함수로 작성하게 되면 훨씬 편리할 것 같습니다. 그래서 제네릭을 사용합니다.

Generic Functions (제네릭 함수)

제네릭 함수는 모든 타입과 함께 동작 가능합니다. 위 swapTwoInts 함수의 제네릭 버전입니다.

func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
    let temporaryA = a
    a = b
    b = temporaryA
}

모양을 비교해보면,

func swapTwoValues<T>(_ a: inout T, _ b: inout T)
func swapTwoInts(_ a: inout Int, _ b: inout Int)

함수의 제네릭 버전은 실제 타입 대신 T라는 임의의 타입 이름을 사용합니다(다른 문자여도 상관은 없으며 보통 의미관계가 없다면 단일 문자를 사용합니다). 실제 타입은 swapTwoValues 함수가 호출될 때 결정됩니다.

실행 결과는 아래와 같습니다.

var someInt = 3
var anotherInt = 107
swapTwoValues(&someInt, &anotherInt)
// someInt is now 107, and anotherInt is now 3

var someString = "hello"
var anotherString = "world"
swapTwoValues(&someString, &anotherString)
// someString is now "world", and anotherString is now "hello"

참고)

https://docs.swift.org/swift-book/LanguageGuide/Generics.html

[

Generics — The Swift Programming Language (Swift 5.5)

Generics 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. Gener

docs.swift.org

](https://docs.swift.org/swift-book/LanguageGuide/Generics.html)

https://bbiguduk.gitbook.io/swift/language-guide-1/generics

profile
deprecated

0개의 댓글