SlideShare a Scribd company logo
swift 0x17
Generics
문현진(arnold@css99.co.kr)
오늘은 뭘 바를까? 이번 신상은 뭘까? 궁금한 언니들은 구글 플레이에
서 “마메스"를 검색하세요.
제네릭이 필요 할 때
swapTwoInts swapTwoStrings swapTwoDoubles
?
제네릭 함수들
func swapTwoValues<T>(inout a: T, inout b: T) {
let temporaryA = a
a = b
b = temporaryA
}
타입 파라메터
T?
타입 파라메터
ABCDEFGHIJKLMNOPQR...?
타입 파라메터 이름
KeyType? MyName?
타입 파라메터 이름
UpperCamelCase
타입 파라메터 이름
제네릭 타입들
제네릭 타입들
비 제네릭
struct IntStack {
var items = Int[]()
mutating func push(item: Int) {
items.append(item)
}
mutating func pop() -> Int {
return items.removeLast()
}
}
제네릭 타입들
제네릭
struct Stack<T> {
var items = T[]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
}
제네릭 타입들
var stackOfStrings = Stack<String>()
stackOfStrings.push("uno")
stackOfStrings.push("dos")
stackOfStrings.push("tres")
stackOfStrings.push("cuatro")
타입 제약 문법
func someFunction<T: SomeClass, U: SomeProtocol>(someT: T, someU: U) {
// function body goes here
}
타입 제약 문법
func findIndex<T>(array: [T], valueToFind: T) -> Int? {
for (index, value) in enumerate(array) {
if value == valueToFind {
return index
}
}
return nil
}
타입 제약 문법
func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
for (index, value) in enumerate(array) {
if value == valueToFind {
return index
}
}
return nil
}
연관 타입 활용
protocol Container {
typealias ItemType mutating func append(item: ItemType)
var count: Int { get } subscript(i: Int) -> ItemType { get } }
연관 타입 활용
struct IntStack: Container {
// original IntStack implementation
var items = Int[]()
mutating func push(item: Int) {
items.append(item)
}
mutating func pop() -> Int {
return items.removeLast()
}
// conformance to the Container protocol
typealias ItemType = Int mutating func append(item: Int) {
self.push(item)
} var count: Int {
return items.count
} subscript(i: Int) -> Int {
return items[i]
} }
연관 타입 활용
struct Stack<T>: Container {
// original Stack<T> implementation
var items = T[]() mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
// conformance to the Container protocol
mutating func append(item: T) {
self.push(item)
} var count: Int {
return items.count
} subscript(i: Int) -> T {
return items[i]
} }
기존 타입을 연관 타입을 지정 할 수 있도록 확
장 하기
extension Array: Container {}
where
func allItemsMatch<
C1: Container, C2: Container
where C1.ItemType == C2.ItemType, C1.ItemType: Equatable>
(someContainer: C1, anotherContainer: C2) -> Bool {
// 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 are equivalent
for i in 0..someContainer.count {
if someContainer[i] != anotherContainer[i] {
return false
}
}
// all items match, so return true
return true
}

More Related Content

What's hot

Realm.io for iOS
Realm.io for iOSRealm.io for iOS
Realm.io for iOS
Eunjoo Im
 
7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍
Hyunsoo Jung
 
7가지 동시성 모델 4장
7가지 동시성 모델 4장7가지 동시성 모델 4장
7가지 동시성 모델 4장
HyeonSeok Choi
 
HolubOnPatterns/chapter3_3
HolubOnPatterns/chapter3_3HolubOnPatterns/chapter3_3
HolubOnPatterns/chapter3_3suitzero
 
7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성
HyeonSeok Choi
 
이것이 자바다 Chap.14 람다식 Lambda expression(java)(KOR)
이것이 자바다 Chap.14 람다식 Lambda expression(java)(KOR)이것이 자바다 Chap.14 람다식 Lambda expression(java)(KOR)
이것이 자바다 Chap.14 람다식 Lambda expression(java)(KOR)
MIN SEOK KOO
 
Protocol Oriented Programming in Swift
Protocol Oriented Programming in SwiftProtocol Oriented Programming in Swift
Protocol Oriented Programming in Swift
SeongGyu Jo
 
자바8 스트림 API 소개
자바8 스트림 API 소개자바8 스트림 API 소개
자바8 스트림 API 소개
beom kyun choi
 
[Swift] Iterator
[Swift] Iterator[Swift] Iterator
[Swift] Iterator
Bill Kim
 
[devil's camp] - 알고리즘 대회와 STL (박인서)
[devil's camp] - 알고리즘 대회와 STL (박인서)[devil's camp] - 알고리즘 대회와 STL (박인서)
[devil's camp] - 알고리즘 대회와 STL (박인서)
NAVER D2
 
파이썬+Operator+이해하기 20160409
파이썬+Operator+이해하기 20160409파이썬+Operator+이해하기 20160409
파이썬+Operator+이해하기 20160409
Yong Joon Moon
 
[GPG 스터디] 1.4 게임프로그래밍에서의 STL 활용
[GPG 스터디] 1.4 게임프로그래밍에서의 STL 활용 [GPG 스터디] 1.4 게임프로그래밍에서의 STL 활용
[GPG 스터디] 1.4 게임프로그래밍에서의 STL 활용
Sehyeon Nam
 
Stl vector, list, map
Stl vector, list, mapStl vector, list, map
Stl vector, list, map
Nam Hyeonuk
 
Java8 람다
Java8 람다Java8 람다
Java8 람다
Jong Woo Rhee
 
C++ VECTOR, LIST, MAP
C++ VECTOR, LIST, MAPC++ VECTOR, LIST, MAP
C++ VECTOR, LIST, MAP
Jae Woo Woo
 
[새차원, 코틀린(Kotlin) 강좌] 5. Control Flow
[새차원, 코틀린(Kotlin) 강좌] 5. Control Flow[새차원, 코틀린(Kotlin) 강좌] 5. Control Flow
[새차원, 코틀린(Kotlin) 강좌] 5. Control Flow
정연 최
 
나에 첫번째 자바8 람다식 지앤선
나에 첫번째 자바8 람다식   지앤선나에 첫번째 자바8 람다식   지앤선
나에 첫번째 자바8 람다식 지앤선daewon jeong
 
iOS 메모리관리
iOS 메모리관리iOS 메모리관리
iOS 메모리관리
Changwon National University
 
자바8 람다 나머지 공개
자바8 람다 나머지 공개자바8 람다 나머지 공개
자바8 람다 나머지 공개
Sungchul Park
 
포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++
KWANGIL KIM
 

What's hot (20)

Realm.io for iOS
Realm.io for iOSRealm.io for iOS
Realm.io for iOS
 
7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍
 
7가지 동시성 모델 4장
7가지 동시성 모델 4장7가지 동시성 모델 4장
7가지 동시성 모델 4장
 
HolubOnPatterns/chapter3_3
HolubOnPatterns/chapter3_3HolubOnPatterns/chapter3_3
HolubOnPatterns/chapter3_3
 
7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성
 
이것이 자바다 Chap.14 람다식 Lambda expression(java)(KOR)
이것이 자바다 Chap.14 람다식 Lambda expression(java)(KOR)이것이 자바다 Chap.14 람다식 Lambda expression(java)(KOR)
이것이 자바다 Chap.14 람다식 Lambda expression(java)(KOR)
 
Protocol Oriented Programming in Swift
Protocol Oriented Programming in SwiftProtocol Oriented Programming in Swift
Protocol Oriented Programming in Swift
 
자바8 스트림 API 소개
자바8 스트림 API 소개자바8 스트림 API 소개
자바8 스트림 API 소개
 
[Swift] Iterator
[Swift] Iterator[Swift] Iterator
[Swift] Iterator
 
[devil's camp] - 알고리즘 대회와 STL (박인서)
[devil's camp] - 알고리즘 대회와 STL (박인서)[devil's camp] - 알고리즘 대회와 STL (박인서)
[devil's camp] - 알고리즘 대회와 STL (박인서)
 
파이썬+Operator+이해하기 20160409
파이썬+Operator+이해하기 20160409파이썬+Operator+이해하기 20160409
파이썬+Operator+이해하기 20160409
 
[GPG 스터디] 1.4 게임프로그래밍에서의 STL 활용
[GPG 스터디] 1.4 게임프로그래밍에서의 STL 활용 [GPG 스터디] 1.4 게임프로그래밍에서의 STL 활용
[GPG 스터디] 1.4 게임프로그래밍에서의 STL 활용
 
Stl vector, list, map
Stl vector, list, mapStl vector, list, map
Stl vector, list, map
 
Java8 람다
Java8 람다Java8 람다
Java8 람다
 
C++ VECTOR, LIST, MAP
C++ VECTOR, LIST, MAPC++ VECTOR, LIST, MAP
C++ VECTOR, LIST, MAP
 
[새차원, 코틀린(Kotlin) 강좌] 5. Control Flow
[새차원, 코틀린(Kotlin) 강좌] 5. Control Flow[새차원, 코틀린(Kotlin) 강좌] 5. Control Flow
[새차원, 코틀린(Kotlin) 강좌] 5. Control Flow
 
나에 첫번째 자바8 람다식 지앤선
나에 첫번째 자바8 람다식   지앤선나에 첫번째 자바8 람다식   지앤선
나에 첫번째 자바8 람다식 지앤선
 
iOS 메모리관리
iOS 메모리관리iOS 메모리관리
iOS 메모리관리
 
자바8 람다 나머지 공개
자바8 람다 나머지 공개자바8 람다 나머지 공개
자바8 람다 나머지 공개
 
포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++
 

Viewers also liked

Real World Generics In Swift
Real World Generics In SwiftReal World Generics In Swift
Real World Generics In Swift
Vadym Markov
 
Generics With Swift
Generics With SwiftGenerics With Swift
Generics With Swift
Hirakawa Akira
 
Adopting Swift Generics
Adopting Swift GenericsAdopting Swift Generics
Adopting Swift Generics
Max Sokolov
 
Generics programming in Swift
Generics programming in SwiftGenerics programming in Swift
Generics programming in Swift
Vijaya Prakash Kandel
 
Swift Generics in Theory and Practice
Swift Generics in Theory and PracticeSwift Generics in Theory and Practice
Swift Generics in Theory and Practice
Michele Titolo
 
Java Generics: a deep dive
Java Generics: a deep diveJava Generics: a deep dive
Java Generics: a deep dive
Bryan Basham
 
Advanced Swift Generics
Advanced Swift GenericsAdvanced Swift Generics
Advanced Swift Generics
Max Sokolov
 

Viewers also liked (7)

Real World Generics In Swift
Real World Generics In SwiftReal World Generics In Swift
Real World Generics In Swift
 
Generics With Swift
Generics With SwiftGenerics With Swift
Generics With Swift
 
Adopting Swift Generics
Adopting Swift GenericsAdopting Swift Generics
Adopting Swift Generics
 
Generics programming in Swift
Generics programming in SwiftGenerics programming in Swift
Generics programming in Swift
 
Swift Generics in Theory and Practice
Swift Generics in Theory and PracticeSwift Generics in Theory and Practice
Swift Generics in Theory and Practice
 
Java Generics: a deep dive
Java Generics: a deep diveJava Generics: a deep dive
Java Generics: a deep dive
 
Advanced Swift Generics
Advanced Swift GenericsAdvanced Swift Generics
Advanced Swift Generics
 

Similar to Swift 0x17 generics

[Swift] Functions
[Swift] Functions[Swift] Functions
[Swift] Functions
Bill Kim
 
5장 객체와클래스
5장 객체와클래스5장 객체와클래스
5장 객체와클래스
SeoYeong
 
[Swift] Data Structure - Stack
[Swift] Data Structure - Stack[Swift] Data Structure - Stack
[Swift] Data Structure - Stack
Bill Kim
 
Collection framework
Collection frameworkCollection framework
Collection framework
ssuser34b989
 
파이썬정리 20160130
파이썬정리 20160130파이썬정리 20160130
파이썬정리 20160130
Yong Joon Moon
 
Java stream v0.1
Java stream v0.1Java stream v0.1
Java stream v0.1
Hyosang Hong
 
Java stream v0.1
Java stream v0.1Java stream v0.1
Java stream v0.1
Hyosang Hong
 
05 컬렉션제너릭
05 컬렉션제너릭05 컬렉션제너릭
05 컬렉션제너릭
rjawptlsghk
 
2014.07.26 KSUG와 지앤선이 함께하는 테크니컬 세미나 - 나의 첫번째 자바8 람다식 (정대원)
2014.07.26 KSUG와 지앤선이 함께하는 테크니컬 세미나 - 나의 첫번째 자바8 람다식 (정대원)2014.07.26 KSUG와 지앤선이 함께하는 테크니컬 세미나 - 나의 첫번째 자바8 람다식 (정대원)
2014.07.26 KSUG와 지앤선이 함께하는 테크니컬 세미나 - 나의 첫번째 자바8 람다식 (정대원)
JiandSon
 
C++ Advanced 강의 4주차
 C++ Advanced 강의 4주차 C++ Advanced 강의 4주차
C++ Advanced 강의 4주차
HyunJoon Park
 
STL study (skyLab)
STL study (skyLab)STL study (skyLab)
STL study (skyLab)
Gyeongwook Choi
 
[Swift] Generics
[Swift] Generics[Swift] Generics
[Swift] Generics
Bill Kim
 
Item10. toString 메소드는 항상 오버라이드 하자
Item10. toString 메소드는 항상 오버라이드  하자Item10. toString 메소드는 항상 오버라이드  하자
Item10. toString 메소드는 항상 오버라이드 하자
Sungho Moon
 
자바 테스트 자동화
자바 테스트 자동화자바 테스트 자동화
자바 테스트 자동화
Sungchul Park
 
Swift3 : class and struct(+property+method)
Swift3 : class and struct(+property+method)Swift3 : class and struct(+property+method)
Swift3 : class and struct(+property+method)
승욱 정
 

Similar to Swift 0x17 generics (20)

[Swift] Functions
[Swift] Functions[Swift] Functions
[Swift] Functions
 
5장 객체와클래스
5장 객체와클래스5장 객체와클래스
5장 객체와클래스
 
[Swift] Data Structure - Stack
[Swift] Data Structure - Stack[Swift] Data Structure - Stack
[Swift] Data Structure - Stack
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
파이썬정리 20160130
파이썬정리 20160130파이썬정리 20160130
파이썬정리 20160130
 
강의자료5
강의자료5강의자료5
강의자료5
 
Java stream v0.1
Java stream v0.1Java stream v0.1
Java stream v0.1
 
Java stream v0.1
Java stream v0.1Java stream v0.1
Java stream v0.1
 
05 컬렉션제너릭
05 컬렉션제너릭05 컬렉션제너릭
05 컬렉션제너릭
 
2014.07.26 KSUG와 지앤선이 함께하는 테크니컬 세미나 - 나의 첫번째 자바8 람다식 (정대원)
2014.07.26 KSUG와 지앤선이 함께하는 테크니컬 세미나 - 나의 첫번째 자바8 람다식 (정대원)2014.07.26 KSUG와 지앤선이 함께하는 테크니컬 세미나 - 나의 첫번째 자바8 람다식 (정대원)
2014.07.26 KSUG와 지앤선이 함께하는 테크니컬 세미나 - 나의 첫번째 자바8 람다식 (정대원)
 
강의자료4
강의자료4강의자료4
강의자료4
 
C++ Advanced 강의 4주차
 C++ Advanced 강의 4주차 C++ Advanced 강의 4주차
C++ Advanced 강의 4주차
 
STL study (skyLab)
STL study (skyLab)STL study (skyLab)
STL study (skyLab)
 
강의자료3
강의자료3강의자료3
강의자료3
 
C review
C  reviewC  review
C review
 
[Swift] Generics
[Swift] Generics[Swift] Generics
[Swift] Generics
 
Item10. toString 메소드는 항상 오버라이드 하자
Item10. toString 메소드는 항상 오버라이드  하자Item10. toString 메소드는 항상 오버라이드  하자
Item10. toString 메소드는 항상 오버라이드 하자
 
자바 테스트 자동화
자바 테스트 자동화자바 테스트 자동화
자바 테스트 자동화
 
Move semantic
Move semanticMove semantic
Move semantic
 
Swift3 : class and struct(+property+method)
Swift3 : class and struct(+property+method)Swift3 : class and struct(+property+method)
Swift3 : class and struct(+property+method)
 

More from Hyun Jin Moon

Swift 0x19 advanced operators
Swift 0x19 advanced operatorsSwift 0x19 advanced operators
Swift 0x19 advanced operators
Hyun Jin Moon
 
Swift 0x18 access control
Swift 0x18 access controlSwift 0x18 access control
Swift 0x18 access control
Hyun Jin Moon
 
Swift 0x14 nested types
Swift 0x14 nested typesSwift 0x14 nested types
Swift 0x14 nested types
Hyun Jin Moon
 
Swift 0x12 optional chaining
Swift 0x12 optional chainingSwift 0x12 optional chaining
Swift 0x12 optional chaining
Hyun Jin Moon
 
Swift 0x0e 초기화
Swift 0x0e 초기화Swift 0x0e 초기화
Swift 0x0e 초기화
Hyun Jin Moon
 
Swift 0x0d 상속
Swift 0x0d 상속Swift 0x0d 상속
Swift 0x0d 상속
Hyun Jin Moon
 
Swift 0x0c 서브스크립트
Swift 0x0c 서브스크립트Swift 0x0c 서브스크립트
Swift 0x0c 서브스크립트
Hyun Jin Moon
 
Swift 0x02 기본 연산자
Swift 0x02   기본 연산자Swift 0x02   기본 연산자
Swift 0x02 기본 연산자
Hyun Jin Moon
 
Swift 0x01 환경 설정
Swift 0x01   환경 설정Swift 0x01   환경 설정
Swift 0x01 환경 설정
Hyun Jin Moon
 
Shell, merge, heap sort
Shell, merge, heap sortShell, merge, heap sort
Shell, merge, heap sort
Hyun Jin Moon
 
Djang Beginning 2
Djang Beginning 2Djang Beginning 2
Djang Beginning 2
Hyun Jin Moon
 
Programming challange crypt_kicker
Programming challange crypt_kickerProgramming challange crypt_kicker
Programming challange crypt_kicker
Hyun Jin Moon
 
Node.js Cloud Service Publish
Node.js Cloud Service PublishNode.js Cloud Service Publish
Node.js Cloud Service Publish
Hyun Jin Moon
 

More from Hyun Jin Moon (14)

Swift 0x19 advanced operators
Swift 0x19 advanced operatorsSwift 0x19 advanced operators
Swift 0x19 advanced operators
 
Swift 0x18 access control
Swift 0x18 access controlSwift 0x18 access control
Swift 0x18 access control
 
Swift 0x14 nested types
Swift 0x14 nested typesSwift 0x14 nested types
Swift 0x14 nested types
 
Swift 0x12 optional chaining
Swift 0x12 optional chainingSwift 0x12 optional chaining
Swift 0x12 optional chaining
 
Swift 0x0e 초기화
Swift 0x0e 초기화Swift 0x0e 초기화
Swift 0x0e 초기화
 
Swift 0x0d 상속
Swift 0x0d 상속Swift 0x0d 상속
Swift 0x0d 상속
 
Swift 0x0c 서브스크립트
Swift 0x0c 서브스크립트Swift 0x0c 서브스크립트
Swift 0x0c 서브스크립트
 
Swift 0x02 기본 연산자
Swift 0x02   기본 연산자Swift 0x02   기본 연산자
Swift 0x02 기본 연산자
 
Swift 0x01 환경 설정
Swift 0x01   환경 설정Swift 0x01   환경 설정
Swift 0x01 환경 설정
 
Quick, Tree sort
Quick, Tree sortQuick, Tree sort
Quick, Tree sort
 
Shell, merge, heap sort
Shell, merge, heap sortShell, merge, heap sort
Shell, merge, heap sort
 
Djang Beginning 2
Djang Beginning 2Djang Beginning 2
Djang Beginning 2
 
Programming challange crypt_kicker
Programming challange crypt_kickerProgramming challange crypt_kicker
Programming challange crypt_kicker
 
Node.js Cloud Service Publish
Node.js Cloud Service PublishNode.js Cloud Service Publish
Node.js Cloud Service Publish
 

Swift 0x17 generics

Editor's Notes

  1. 두 개의 숫자 또는 문자열을 교환하는 함수이다. 여러가지 종류가 있다. 모든 타입을 고려하려면?
  2. 이걸 설명 하기 전에 스택을 예제로 들것 이기 때문에 스택의 특성을 본다.
  3. 이 함수는 에러가 납니다. 왜냐면 타입 T가 반드시 비교가 가능한 == 연산자와 != 를 사용 할 수 있다는 보장이 없기 때문입니다.
  4. 이 함수는 에러가 납니다. 왜냐면 타입 T가 반드시 비교가 가능한 == 연산자와 != 를 사용 할 수 있다는 보장이 없기 때문입니다.