지네릭 (Generics)

Swift ) Generic

지네릭 함수 (Generic Functions)

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

→ 플레이스 홀더 T는 어떤 타입이어야 하는지 명시하지 않고, 두 인자의 타입이 같다는 것만 알림

→ 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"

→ Int, String 모두 사용 가능

→ 같은 기능을 하는 함수들을 타입마다 새로 만들 필요 없이, 타입 파라미터 <T> 사용

타입 제한 (Type Constraints)

: 특정한 타입만 Generic 함수를 사용하고자 할 때 사용

func someFunction<T: SomeClass, U: SomeProtocol>(someT: T, someU: U) {
	// function body goes here
}