SlideShare a Scribd company logo
1 of 15
Download to read offline
SWIFT
Generics
Bill Kim(김정훈) | ibillkim@gmail.com
목차
•Generics
•Generic Functions
•Type Parameters
•Generic Types
•Type Constraints
•Associated Types
•Generic Where Clauses
•References
Generics
Generic을 사용하면 재사용 가능하고 유연한 코드를 작성할 수 있
습니다.
Swift에서 제공하는 C++에서의 템플릿과 유사한 개념이라고 생각
할 수 있습니다.
Generic Functions
Generic을 함수에서 사용하면 아래와 같이 사용할 수 있습니다.
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
}
// Generics 함수를 사용하여 다음과 같이 다양한 타입의 파라미터를 받을 수 있습니다.
func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
let temporaryA = a
a = b
b = temporaryA
}
swapTwoValues(&someInt, &anotherInt)
swapTwoValues(&someString, &anotherString)
Type Parameters
앞에서 사용한 플레이스 홀더 T는 타입 파라미터의 예입니다.
타입 파라미터는 플레이스 홀더 타입의 이름을 명시하고 함수명 바
로 뒤에 적어줍니다. 그리고 와 같이 꺽쇄로 묶어 줍니다.
타입 파라미터를 한번 선언하면 이 것을 함수의 타입으로 사용할
수 있습니다.
복수의 타입 파라미터를 사용할때는 콤마로 구분해 줍니다.
Dictionary의 Key, Value와 같이 엘리먼트 간의 서로 상관관계
가 있는 경우 의미가 있는 이름을 파라미터 이름으로 붙이고 그렇
지 않은 경우는 T, U, V와 같은 단일 문자로 파라미터 이름을 짓습
니다.
Generic Types
제네릭 함수에 추가로 Swift에서는 제네릭 타입을 정의할 수 있습
니다.
제네릭 타입이란 “타입을 파라미터화해서 컴파일시 구체적인 타입
이 결정되도록 하는 것“이란 뜻으로 Swift에서도 제네릭 타입을 지
원합니다.
// EEItem: 임의로 설정한 이름으로 어떠한 타입도 받을 수 있음
func makeArray<EEItem>(repeating item: EEItem, numberOfTimes: Int) ->
[EEItem] {
var result = [EEItem]() // 배열의 초기화
for _ in 0 ..< numberOfTimes {
result.append(item)
}
return result
}
let res1 = makeArray(repeating: "knock", numberOfTimes: 5)
print(res1)
Type Constraints
Swift의 Dictionary 타입은 key값을 사용합니다.
이때 key는 유일한 값이어야 하기 때문에 hashable이라는 프로토
콜을 반드지 따라야 합니다.
이와 같이 Generics은 특정 타입이 반드시 어떤 프로토콜을 따라
야 하도록 타입에 대한 제한을 설정할 수 있습니다.
func findIndex<T: Equatable>(of valueToFind: T, in array:[T]) -> Int? {
for (index, value) in array.enumerated() {
// == 등호 메소드를 사용하기 위해서는 두 값 혹은 객체가 반드시
// Equatable 프로토콜을 따라야한다.
if value == valueToFind {
return index
}
}
return nil
}
Associated Types
연관타입(Associated Types)은 프로토콜의 일부분으로 타입에 플레이스홀더 이
름을 부여합니다.
다시 말해 특정 타입을 동적으로 지정해 사용할 수 있습니다.
associatedtype를 사용하여 지정하면 해당 Item은 어떤 타입도 될 수 있습니다.
protocol Container {
associatedtype Item
var count: Int { get }
}
struct IntStack: Container {
// Item을 Int형으로 선언해 사용합니다.
typealias Item = Int
var items = [Int]()
mutating func push(_ item: Int) {
items.append(item)
}
mutating func pop() -> Int {
return items.removeLast()
}
var count: Int {
return items.count
}
}
Generic Where Clauses
제네릭에서도 where절을 사용할 수 있습니다.
// Container C1, C2를 비교하며 모든 값이 같을 때 true를 반환
func allItemsMatch<C1: Container, C2: Container>
(_ someContainer: C1, _ anotherContainer: C2) -> Bool
where C1.Item == C2.Item, C1.Item: Equatable
{
// Check that both containers contain the same number of items.
if someContainer.count != anotherContainer.count {
return false
}
// Check each pair of items to see if they're equivalent.
for i in 0..< someContainer.count {
if someContainer[i] != anotherContainer[i] {
return false
}
}
// All items match, so return true.
return true
}
Generic Where Clauses
제네릭의 익스텐션을 선언할때 where절을 포함시킬 수 있습니다.
extension Stack where Element: Equatable {
func isTop(_ item: Element) -> Bool {
guard let topItem = items.last else {
return false
}
// Element 을 Equatable 프로토콜을 따르도록 하였기에 컴파일 에러 미발생
return topItem == item
}
}
Generic Where Clauses
연관 타입(Associated Types)에도 where절을 적용해 제한을 둘
수 있습니다.
protocol Container {
associatedtype Item
mutating func append(_ item: Item)
var count: Int { get }
subscript(i: Int) -> Item { get }
associatedtype Iterator: IteratorProtocol where Iterator.Element == Item
func makeIterator() -> Iterator
}
// 다른 프로토콜을 상속하는 프로토콜에도 where절로 조건을 부여할 수 있습니다.
protocol ComparableContainer: Container where Item: Comparable { }
Generic Where Clauses
제네릭의 서브스크립트에도 조건(where)을 걸 수 있습니다.
protocol Container {
associatedtype Item
mutating func append(_ item: Item)
var count: Int { get }
subscript(i: Int) -> Item { get }
}
extension Container {
subscript<Indices: Sequence>(indices: Indices) -> [Item]
where Indices.Iterator.Element == Int {
var result = [Item]()
for index in indices {
result.append(self[index])
}
return result
}
}
References
[1] [Swift]Generics 정리 : http://minsone.github.io/mac/
ios/swift-generics-summary
[2] Swift ) Generic : https://zeddios.tistory.com/226
[3] Generic Parameters and Arguments : https://
docs.swift.org/swift-book/ReferenceManual/
GenericParametersAndArguments.html
[4] 제네릭(Generics) : https://kka7.tistory.com/128
[5] Swift Generics Tutorial: https://
www.raywenderlich.com/3535703-swift-generics-
tutorial-getting-started
References
[6] [Swift] 프로토콜과 제네릭 그리고 열거형 : https://baked-
corn.tistory.com/133
[7] Generics in Swift 4 : https://medium.com/
developermind/generics-in-swift-4-4f802cd6f53c
[8] Swift) 제네릭(Generics) : https://atelier-chez-
moi.tistory.com/80
[9] Generics : https://www.swiftbysundell.com/basics/
generics/
[10] Swift - Generics : https://www.tutorialspoint.com/
swift/swift_generics.htm
Thank you!

More Related Content

What's hot

[2011 05 21] 4장 제어
[2011 05 21] 4장 제어[2011 05 21] 4장 제어
[2011 05 21] 4장 제어Jong Pil Won
 
Effective c++ Chapter1,2
Effective c++ Chapter1,2Effective c++ Chapter1,2
Effective c++ Chapter1,2문익 장
 
Start IoT with JavaScript - 1.기초
Start IoT with JavaScript - 1.기초Start IoT with JavaScript - 1.기초
Start IoT with JavaScript - 1.기초Park Jonggun
 
Javascript - Function
Javascript - FunctionJavascript - Function
Javascript - Functionwonmin lee
 
[2011 05 21] 4장 제어
[2011 05 21] 4장 제어[2011 05 21] 4장 제어
[2011 05 21] 4장 제어Jong Pil Won
 
Effective cpp
Effective cppEffective cpp
Effective cppTonyCms
 
연산자 오버로딩
연산자 오버로딩연산자 오버로딩
연산자 오버로딩수빈 박
 
비개발자를 위한 Javascript 알아가기 #6
비개발자를 위한 Javascript 알아가기 #6비개발자를 위한 Javascript 알아가기 #6
비개발자를 위한 Javascript 알아가기 #6민태 김
 
Cpp에서 활용해보는 Lambda식
Cpp에서 활용해보는 Lambda식Cpp에서 활용해보는 Lambda식
Cpp에서 활용해보는 Lambda식TonyCms
 
[Swift] Functions
[Swift] Functions[Swift] Functions
[Swift] FunctionsBill Kim
 
외계어 스터디 3/5 function and object
외계어 스터디 3/5   function and object외계어 스터디 3/5   function and object
외계어 스터디 3/5 function and object민태 김
 
Swift3 generic
Swift3 genericSwift3 generic
Swift3 genericEunjoo Im
 
비개발자를 위한 Javascript 알아가기 #5
비개발자를 위한 Javascript 알아가기 #5비개발자를 위한 Javascript 알아가기 #5
비개발자를 위한 Javascript 알아가기 #5민태 김
 
You don't know JS / this / chapter 1-2
You don't know JS / this / chapter 1-2You don't know JS / this / chapter 1-2
You don't know JS / this / chapter 1-2Kiwoong Kwon
 
03. function in typescript
03. function in typescript03. function in typescript
03. function in typescriptHan JaeYeab
 
호이스팅, 클로저, IIFE
호이스팅, 클로저, IIFE호이스팅, 클로저, IIFE
호이스팅, 클로저, IIFEChangHyeon Bae
 

What's hot (20)

[2011 05 21] 4장 제어
[2011 05 21] 4장 제어[2011 05 21] 4장 제어
[2011 05 21] 4장 제어
 
Effective c++ Chapter1,2
Effective c++ Chapter1,2Effective c++ Chapter1,2
Effective c++ Chapter1,2
 
Start IoT with JavaScript - 1.기초
Start IoT with JavaScript - 1.기초Start IoT with JavaScript - 1.기초
Start IoT with JavaScript - 1.기초
 
Javascript - Function
Javascript - FunctionJavascript - Function
Javascript - Function
 
[2011 05 21] 4장 제어
[2011 05 21] 4장 제어[2011 05 21] 4장 제어
[2011 05 21] 4장 제어
 
Effective cpp
Effective cppEffective cpp
Effective cpp
 
연산자 오버로딩
연산자 오버로딩연산자 오버로딩
연산자 오버로딩
 
비개발자를 위한 Javascript 알아가기 #6
비개발자를 위한 Javascript 알아가기 #6비개발자를 위한 Javascript 알아가기 #6
비개발자를 위한 Javascript 알아가기 #6
 
Cpp에서 활용해보는 Lambda식
Cpp에서 활용해보는 Lambda식Cpp에서 활용해보는 Lambda식
Cpp에서 활용해보는 Lambda식
 
[Swift] Functions
[Swift] Functions[Swift] Functions
[Swift] Functions
 
외계어 스터디 3/5 function and object
외계어 스터디 3/5   function and object외계어 스터디 3/5   function and object
외계어 스터디 3/5 function and object
 
Prototype
PrototypePrototype
Prototype
 
07. type system
07. type system07. type system
07. type system
 
01. basic types
01. basic types01. basic types
01. basic types
 
Swift3 generic
Swift3 genericSwift3 generic
Swift3 generic
 
비개발자를 위한 Javascript 알아가기 #5
비개발자를 위한 Javascript 알아가기 #5비개발자를 위한 Javascript 알아가기 #5
비개발자를 위한 Javascript 알아가기 #5
 
You don't know JS / this / chapter 1-2
You don't know JS / this / chapter 1-2You don't know JS / this / chapter 1-2
You don't know JS / this / chapter 1-2
 
03. function in typescript
03. function in typescript03. function in typescript
03. function in typescript
 
Scala syntax function
Scala syntax functionScala syntax function
Scala syntax function
 
호이스팅, 클로저, IIFE
호이스팅, 클로저, IIFE호이스팅, 클로저, IIFE
호이스팅, 클로저, IIFE
 

Similar to [Swift] Generics

[2011 05 21] 4장 제어
[2011 05 21] 4장 제어[2011 05 21] 4장 제어
[2011 05 21] 4장 제어Jong Pil Won
 
NHNNEXT 개경프14 Subway Rocket Team Study 3rd C++
NHNNEXT 개경프14 Subway Rocket Team Study 3rd C++NHNNEXT 개경프14 Subway Rocket Team Study 3rd C++
NHNNEXT 개경프14 Subway Rocket Team Study 3rd C++Min-soo Park
 
헷갈리는 자바스크립트 정리
헷갈리는 자바스크립트 정리헷갈리는 자바스크립트 정리
헷갈리는 자바스크립트 정리은숙 이
 
Python 이해하기 20160815
Python 이해하기 20160815Python 이해하기 20160815
Python 이해하기 20160815Yong Joon Moon
 
Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기jongho jeong
 
자바스크립트 함수
자바스크립트 함수자바스크립트 함수
자바스크립트 함수유진 변
 
프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oop프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oopYoung-Beom Rhee
 
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍Young-Beom Rhee
 
0.javascript기본(~3일차내)
0.javascript기본(~3일차내)0.javascript기본(~3일차내)
0.javascript기본(~3일차내)Sung-hoon Ma
 
JavaScript Fundermetal
JavaScript FundermetalJavaScript Fundermetal
JavaScript FundermetalKwangho SEO
 
[스프링 스터디 3일차] @MVC
[스프링 스터디 3일차] @MVC[스프링 스터디 3일차] @MVC
[스프링 스터디 3일차] @MVCAnselmKim
 
Javascript 완벽 가이드 정리
Javascript 완벽 가이드 정리Javascript 완벽 가이드 정리
Javascript 완벽 가이드 정리ETRIBE_STG
 
More effective c++ chapter1,2
More effective c++ chapter1,2More effective c++ chapter1,2
More effective c++ chapter1,2문익 장
 
Swift3 subscript inheritance initialization
Swift3 subscript inheritance initializationSwift3 subscript inheritance initialization
Swift3 subscript inheritance initializationEunjoo Im
 
나에 첫번째 자바8 람다식 지앤선
나에 첫번째 자바8 람다식   지앤선나에 첫번째 자바8 람다식   지앤선
나에 첫번째 자바8 람다식 지앤선daewon jeong
 
자바 테스트 자동화
자바 테스트 자동화자바 테스트 자동화
자바 테스트 자동화Sungchul Park
 

Similar to [Swift] Generics (20)

[2011 05 21] 4장 제어
[2011 05 21] 4장 제어[2011 05 21] 4장 제어
[2011 05 21] 4장 제어
 
C review
C  reviewC  review
C review
 
NHNNEXT 개경프14 Subway Rocket Team Study 3rd C++
NHNNEXT 개경프14 Subway Rocket Team Study 3rd C++NHNNEXT 개경프14 Subway Rocket Team Study 3rd C++
NHNNEXT 개경프14 Subway Rocket Team Study 3rd C++
 
헷갈리는 자바스크립트 정리
헷갈리는 자바스크립트 정리헷갈리는 자바스크립트 정리
헷갈리는 자바스크립트 정리
 
Python 이해하기 20160815
Python 이해하기 20160815Python 이해하기 20160815
Python 이해하기 20160815
 
Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기
 
자바스크립트 함수
자바스크립트 함수자바스크립트 함수
자바스크립트 함수
 
06장 함수
06장 함수06장 함수
06장 함수
 
프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oop프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oop
 
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
 
Java(3/4)
Java(3/4)Java(3/4)
Java(3/4)
 
0.javascript기본(~3일차내)
0.javascript기본(~3일차내)0.javascript기본(~3일차내)
0.javascript기본(~3일차내)
 
JavaScript Fundermetal
JavaScript FundermetalJavaScript Fundermetal
JavaScript Fundermetal
 
파이썬 심화
파이썬 심화파이썬 심화
파이썬 심화
 
[스프링 스터디 3일차] @MVC
[스프링 스터디 3일차] @MVC[스프링 스터디 3일차] @MVC
[스프링 스터디 3일차] @MVC
 
Javascript 완벽 가이드 정리
Javascript 완벽 가이드 정리Javascript 완벽 가이드 정리
Javascript 완벽 가이드 정리
 
More effective c++ chapter1,2
More effective c++ chapter1,2More effective c++ chapter1,2
More effective c++ chapter1,2
 
Swift3 subscript inheritance initialization
Swift3 subscript inheritance initializationSwift3 subscript inheritance initialization
Swift3 subscript inheritance initialization
 
나에 첫번째 자바8 람다식 지앤선
나에 첫번째 자바8 람다식   지앤선나에 첫번째 자바8 람다식   지앤선
나에 첫번째 자바8 람다식 지앤선
 
자바 테스트 자동화
자바 테스트 자동화자바 테스트 자동화
자바 테스트 자동화
 

More from Bill Kim

[Algorithm] Sorting Comparison
[Algorithm] Sorting Comparison[Algorithm] Sorting Comparison
[Algorithm] Sorting ComparisonBill Kim
 
[Algorithm] Big O Notation
[Algorithm] Big O Notation[Algorithm] Big O Notation
[Algorithm] Big O NotationBill Kim
 
[Algorithm] Shell Sort
[Algorithm] Shell Sort[Algorithm] Shell Sort
[Algorithm] Shell SortBill Kim
 
[Algorithm] Radix Sort
[Algorithm] Radix Sort[Algorithm] Radix Sort
[Algorithm] Radix SortBill Kim
 
[Algorithm] Quick Sort
[Algorithm] Quick Sort[Algorithm] Quick Sort
[Algorithm] Quick SortBill Kim
 
[Algorithm] Heap Sort
[Algorithm] Heap Sort[Algorithm] Heap Sort
[Algorithm] Heap SortBill Kim
 
[Algorithm] Counting Sort
[Algorithm] Counting Sort[Algorithm] Counting Sort
[Algorithm] Counting SortBill Kim
 
[Algorithm] Selection Sort
[Algorithm] Selection Sort[Algorithm] Selection Sort
[Algorithm] Selection SortBill Kim
 
[Algorithm] Merge Sort
[Algorithm] Merge Sort[Algorithm] Merge Sort
[Algorithm] Merge SortBill Kim
 
[Algorithm] Insertion Sort
[Algorithm] Insertion Sort[Algorithm] Insertion Sort
[Algorithm] Insertion SortBill Kim
 
[Algorithm] Bubble Sort
[Algorithm] Bubble Sort[Algorithm] Bubble Sort
[Algorithm] Bubble SortBill Kim
 
[Algorithm] Binary Search
[Algorithm] Binary Search[Algorithm] Binary Search
[Algorithm] Binary SearchBill Kim
 
[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)Bill Kim
 
[Swift] Data Structure - AVL
[Swift] Data Structure - AVL[Swift] Data Structure - AVL
[Swift] Data Structure - AVLBill Kim
 
[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search TreeBill Kim
 
[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)Bill Kim
 
[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)Bill Kim
 
[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary Tree[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary TreeBill Kim
 
[Swift] Data Structure - Tree
[Swift] Data Structure - Tree[Swift] Data Structure - Tree
[Swift] Data Structure - TreeBill Kim
 
[Swift] Data Structure - Graph
[Swift] Data Structure - Graph[Swift] Data Structure - Graph
[Swift] Data Structure - GraphBill Kim
 

More from Bill Kim (20)

[Algorithm] Sorting Comparison
[Algorithm] Sorting Comparison[Algorithm] Sorting Comparison
[Algorithm] Sorting Comparison
 
[Algorithm] Big O Notation
[Algorithm] Big O Notation[Algorithm] Big O Notation
[Algorithm] Big O Notation
 
[Algorithm] Shell Sort
[Algorithm] Shell Sort[Algorithm] Shell Sort
[Algorithm] Shell Sort
 
[Algorithm] Radix Sort
[Algorithm] Radix Sort[Algorithm] Radix Sort
[Algorithm] Radix Sort
 
[Algorithm] Quick Sort
[Algorithm] Quick Sort[Algorithm] Quick Sort
[Algorithm] Quick Sort
 
[Algorithm] Heap Sort
[Algorithm] Heap Sort[Algorithm] Heap Sort
[Algorithm] Heap Sort
 
[Algorithm] Counting Sort
[Algorithm] Counting Sort[Algorithm] Counting Sort
[Algorithm] Counting Sort
 
[Algorithm] Selection Sort
[Algorithm] Selection Sort[Algorithm] Selection Sort
[Algorithm] Selection Sort
 
[Algorithm] Merge Sort
[Algorithm] Merge Sort[Algorithm] Merge Sort
[Algorithm] Merge Sort
 
[Algorithm] Insertion Sort
[Algorithm] Insertion Sort[Algorithm] Insertion Sort
[Algorithm] Insertion Sort
 
[Algorithm] Bubble Sort
[Algorithm] Bubble Sort[Algorithm] Bubble Sort
[Algorithm] Bubble Sort
 
[Algorithm] Binary Search
[Algorithm] Binary Search[Algorithm] Binary Search
[Algorithm] Binary Search
 
[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)
 
[Swift] Data Structure - AVL
[Swift] Data Structure - AVL[Swift] Data Structure - AVL
[Swift] Data Structure - AVL
 
[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree
 
[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)
 
[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)
 
[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary Tree[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary Tree
 
[Swift] Data Structure - Tree
[Swift] Data Structure - Tree[Swift] Data Structure - Tree
[Swift] Data Structure - Tree
 
[Swift] Data Structure - Graph
[Swift] Data Structure - Graph[Swift] Data Structure - Graph
[Swift] Data Structure - Graph
 

[Swift] Generics

  • 2. 목차 •Generics •Generic Functions •Type Parameters •Generic Types •Type Constraints •Associated Types •Generic Where Clauses •References
  • 3. Generics Generic을 사용하면 재사용 가능하고 유연한 코드를 작성할 수 있 습니다. Swift에서 제공하는 C++에서의 템플릿과 유사한 개념이라고 생각 할 수 있습니다.
  • 4. Generic Functions Generic을 함수에서 사용하면 아래와 같이 사용할 수 있습니다. 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 } // Generics 함수를 사용하여 다음과 같이 다양한 타입의 파라미터를 받을 수 있습니다. func swapTwoValues<T>(_ a: inout T, _ b: inout T) { let temporaryA = a a = b b = temporaryA } swapTwoValues(&someInt, &anotherInt) swapTwoValues(&someString, &anotherString)
  • 5. Type Parameters 앞에서 사용한 플레이스 홀더 T는 타입 파라미터의 예입니다. 타입 파라미터는 플레이스 홀더 타입의 이름을 명시하고 함수명 바 로 뒤에 적어줍니다. 그리고 와 같이 꺽쇄로 묶어 줍니다. 타입 파라미터를 한번 선언하면 이 것을 함수의 타입으로 사용할 수 있습니다. 복수의 타입 파라미터를 사용할때는 콤마로 구분해 줍니다. Dictionary의 Key, Value와 같이 엘리먼트 간의 서로 상관관계 가 있는 경우 의미가 있는 이름을 파라미터 이름으로 붙이고 그렇 지 않은 경우는 T, U, V와 같은 단일 문자로 파라미터 이름을 짓습 니다.
  • 6. Generic Types 제네릭 함수에 추가로 Swift에서는 제네릭 타입을 정의할 수 있습 니다. 제네릭 타입이란 “타입을 파라미터화해서 컴파일시 구체적인 타입 이 결정되도록 하는 것“이란 뜻으로 Swift에서도 제네릭 타입을 지 원합니다. // EEItem: 임의로 설정한 이름으로 어떠한 타입도 받을 수 있음 func makeArray<EEItem>(repeating item: EEItem, numberOfTimes: Int) -> [EEItem] { var result = [EEItem]() // 배열의 초기화 for _ in 0 ..< numberOfTimes { result.append(item) } return result } let res1 = makeArray(repeating: "knock", numberOfTimes: 5) print(res1)
  • 7. Type Constraints Swift의 Dictionary 타입은 key값을 사용합니다. 이때 key는 유일한 값이어야 하기 때문에 hashable이라는 프로토 콜을 반드지 따라야 합니다. 이와 같이 Generics은 특정 타입이 반드시 어떤 프로토콜을 따라 야 하도록 타입에 대한 제한을 설정할 수 있습니다. func findIndex<T: Equatable>(of valueToFind: T, in array:[T]) -> Int? { for (index, value) in array.enumerated() { // == 등호 메소드를 사용하기 위해서는 두 값 혹은 객체가 반드시 // Equatable 프로토콜을 따라야한다. if value == valueToFind { return index } } return nil }
  • 8. Associated Types 연관타입(Associated Types)은 프로토콜의 일부분으로 타입에 플레이스홀더 이 름을 부여합니다. 다시 말해 특정 타입을 동적으로 지정해 사용할 수 있습니다. associatedtype를 사용하여 지정하면 해당 Item은 어떤 타입도 될 수 있습니다. protocol Container { associatedtype Item var count: Int { get } } struct IntStack: Container { // Item을 Int형으로 선언해 사용합니다. typealias Item = Int var items = [Int]() mutating func push(_ item: Int) { items.append(item) } mutating func pop() -> Int { return items.removeLast() } var count: Int { return items.count } }
  • 9. Generic Where Clauses 제네릭에서도 where절을 사용할 수 있습니다. // Container C1, C2를 비교하며 모든 값이 같을 때 true를 반환 func allItemsMatch<C1: Container, C2: Container> (_ someContainer: C1, _ anotherContainer: C2) -> Bool where C1.Item == C2.Item, C1.Item: Equatable { // Check that both containers contain the same number of items. if someContainer.count != anotherContainer.count { return false } // Check each pair of items to see if they're equivalent. for i in 0..< someContainer.count { if someContainer[i] != anotherContainer[i] { return false } } // All items match, so return true. return true }
  • 10. Generic Where Clauses 제네릭의 익스텐션을 선언할때 where절을 포함시킬 수 있습니다. extension Stack where Element: Equatable { func isTop(_ item: Element) -> Bool { guard let topItem = items.last else { return false } // Element 을 Equatable 프로토콜을 따르도록 하였기에 컴파일 에러 미발생 return topItem == item } }
  • 11. Generic Where Clauses 연관 타입(Associated Types)에도 where절을 적용해 제한을 둘 수 있습니다. protocol Container { associatedtype Item mutating func append(_ item: Item) var count: Int { get } subscript(i: Int) -> Item { get } associatedtype Iterator: IteratorProtocol where Iterator.Element == Item func makeIterator() -> Iterator } // 다른 프로토콜을 상속하는 프로토콜에도 where절로 조건을 부여할 수 있습니다. protocol ComparableContainer: Container where Item: Comparable { }
  • 12. Generic Where Clauses 제네릭의 서브스크립트에도 조건(where)을 걸 수 있습니다. protocol Container { associatedtype Item mutating func append(_ item: Item) var count: Int { get } subscript(i: Int) -> Item { get } } extension Container { subscript<Indices: Sequence>(indices: Indices) -> [Item] where Indices.Iterator.Element == Int { var result = [Item]() for index in indices { result.append(self[index]) } return result } }
  • 13. References [1] [Swift]Generics 정리 : http://minsone.github.io/mac/ ios/swift-generics-summary [2] Swift ) Generic : https://zeddios.tistory.com/226 [3] Generic Parameters and Arguments : https:// docs.swift.org/swift-book/ReferenceManual/ GenericParametersAndArguments.html [4] 제네릭(Generics) : https://kka7.tistory.com/128 [5] Swift Generics Tutorial: https:// www.raywenderlich.com/3535703-swift-generics- tutorial-getting-started
  • 14. References [6] [Swift] 프로토콜과 제네릭 그리고 열거형 : https://baked- corn.tistory.com/133 [7] Generics in Swift 4 : https://medium.com/ developermind/generics-in-swift-4-4f802cd6f53c [8] Swift) 제네릭(Generics) : https://atelier-chez- moi.tistory.com/80 [9] Generics : https://www.swiftbysundell.com/basics/ generics/ [10] Swift - Generics : https://www.tutorialspoint.com/ swift/swift_generics.htm