SlideShare a Scribd company logo
1 of 16
Download to read offline
SWIFT
Protocol (2/2)
Bill Kim(김정훈) | ibillkim@gmail.com
목차
•Delegation
•Adding Protocols Conformance with an Extension
•Collections of Protocol Types
•Protocol Inheritance
•Class-Only Protocols
•Protocol Composition
•Optional Protocol Requirements
•Protocol ExtensionsChecking for Protocol Conformance
•References
Delegation
위임(Delegation)은 클래스 혹은 구조체 인스턴스에 특정 행위에 대한 책임을 넘길 수 있게 해
주는 디자인 패턴 중 하나입니다.
class Dice {
}
protocol DiceGame {
var dice: Dice { get }
func play()
}
// DiceGameDelegate에 선언해서 실제 DiceGame의 행위와 관련된 구현을
// DiceGameDelegate를 따르는 인스턴스에 위임합니다.
protocol DiceGameDelegate: AnyObject {
func gameDidStart(_ game: DiceGame)
func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int)
func gameDidEnd(_ game: DiceGame)
}
class SnakesAndLadders: DiceGame {
var dice: Dice = Dice()
weak var delegate: DiceGameDelegate?
func play() {
delegate?.gameDidStart(self)
}
func end() {
delegate?.gameDidEnd(self)
}
}
Delegation
class DiceGameTracker: DiceGameDelegate {
var numberOfTurns = 0
func gameDidStart(_ game: DiceGame) {
}
func game(_ game: DiceGame, didStartNewTurnWithDiceRoll
diceRoll: Int) {
}
func gameDidEnd(_ game: DiceGame) {
}
}
let tracker = DiceGameTracker()
let game = SnakesAndLadders()
game.delegate = tracker
game.play()
Adding Protocols Conformance with an Extension
이미 존재하는 타입에 새 프로토콜을 따르게 하기 위해 익스텐션을 사용할 수
있습니다.
원래 값에 접근 권한이 없어도 익스텐션을 사용해 기능을 확장할 수 있습니다.
class Dice {
let sides: Int
init(sides: Int) {
self.sides = sides
}
}
protocol TextRepresentable {
var textualDescription: String { get }
}
extension Dice: TextRepresentable {
var textualDescription: String {
return "A (sides)-sided dice"
}
}
let d12 = Dice(sides: 12)
print(d12.textualDescription) // Prints "A 12-sided dice"
Adding Protocols Conformance with an Extension
만약 어떤 프로토콜을 충족에 필요한 모든 조건을 만족하지만 아직
그 프로토콜을 따른다는 선언을 하지 않았다면 그 선언을 빈 익스텐
션으로 선언할 수 있습니다.
protocol TextRepresentable {
var textualDescription: String { get }
}
struct Hamster {
var name: String
var textualDescription: String {
return "A hamster named (name)"
}
}
// Hamster 인스턴스인 simonTheHamster는 이제 TextRepresentable 타입으로 사용할 수 있습니다.
extension Hamster: TextRepresentable {}
let simonTheHamster = Hamster(name: "Simon")
let somethingTextRepresentable: TextRepresentable = simonTheHamster
print(somethingTextRepresentable.textualDescription) // A hamster named Simon
Collections of Protocol Types
프로토콜을 Array, Dictionary등 Collection 타입에 넣기위한 타
입으로 사용할 수 있습니다.
let d12 = Dice(sides: 12)
let simonTheHamster = Hamster(name: "Simon")
let things: [TextRepresentable] = [d12, simonTheHamster]
for thing in things {
print(thing.textualDescription)
// A 12-sided dice
// A hamster named Simon
}
Protocol Inheritance
클래스 상속같이 프로토콜도 상속할 수 있습니다. 여러 프로토콜을
상속받는 경우 콤마(,)로 구분합니다.
protocol InheritingProtocol : SomeProtocol, AnotherProtocol {
// protocol definition goes here
}
protocol PrettyTextRepresentable : TextRepresentable {
var prettyTextualDescription: String { get }
}
Class-Only Protocols
구조체, 열거형에서 사용하지 않고 클래스 타입에만 사용가능한 프
로토콜을 선언하기 위해서는 프로토콜에 AnyObject를 추가합니
다.
protocol SomeClassOnlyProtocol: AnyObject, SomeInheritedProtocol {
// class-only protocol definition goes here
}
Protocol Composition
동시에 여러 프로토콜을 따르는 타입을 선언할 수 있습니다.
protocol Named {
var name: String { get }
}
protocol Aged {
var age: Int { get }
}
struct Person: Named, Aged {
var name: String
var age: Int
}
func wishHappyBirthday(to celebrator: Named & Aged) {
print("Happy birthday, (celebrator.name), you're (celebrator.age)!")
}
let birthdayPerson = Person(name: "Malcolm", age: 21)
wishHappyBirthday(to: birthdayPerson) // Happy birthday, Malcolm, you're 21!
Optional Protocol Requirements
프로토콜을 선언하면서 필수 구현이 아닌 선택적 구현 조건을 정의
할 수 있습니다.
이 프로토콜의 정의를 위해서 @objc 키워드를 프로토콜 앞에 붙이
고, 개별 함수 혹은 프로퍼티에는 @objc와 optional 키워드를 붙
입니다.
@objc 프로토콜은 클래스 타입에서만 채용될 수 있고 구조체나 열
거형에서는 사용할 수 없습니다.
@objc protocol CounterDataSource {
@objc optional func increment(forCount count: Int) -> Int
@objc optional var fixedIncrement: Int { get }
}
Protocol Extensions
익스텐션을 이용해 프로토콜을 확장할 수 있습니다.
protocol RandomNumberGenerator {
func random() -> Double
}
extension RandomNumberGenerator {
func randomBool() -> Bool {
return random() > 0.5
}
}
class LinearCongruentialGenerator: RandomNumberGenerator {
var lastRandom = 42.0
let m = 139968.0
let a = 3877.0
let c = 29573.0
func random() -> Double {
lastRandom = ((lastRandom * a + c).truncatingRemainder(dividingBy:m))
return lastRandom / m
}
}
let generator = LinearCongruentialGenerator()
print("Here's a random number: (generator.random())")
// Prints "Here's a random number: 0.3746499199817101”
print("And here's a random Boolean: (generator.randomBool())")
// Prints "And here's a random Boolean: true"
Protocol Extensions
프로토콜 익스텐션이 특정 조건에서만 적용되도록 선언할 수 있습니
다. 이 선언에는 where 절을 사용합니다.
다음은 Collection 엘리먼트가 Equatable인 경우에만 적용되는
allEqual()메소드를 구현한 예입니다.
extension Collection where Element: Equatable {
func allEqual() -> Bool {
for element in self {
if element != self.first {
return false
}
}
return true
}
}
let equalNumbers = [100, 100, 100, 100, 100]
let differentNumbers = [100, 100, 200, 100, 200]
print(equalNumbers.allEqual()) // true
print(differentNumbers.allEqual()) // false
References
[1] [Swift]Protocols 정리 : http://minsone.github.io/mac/
ios/swift-protocols-summary
[2] Protocols : https://docs.swift.org/swift-book/
LanguageGuide/Protocols.html
[3] Swift ) Protocols (4) : https://zeddios.tistory.com/347
[4] Swift Protocol 적재적소에 사용하기 : https://
academy.realm.io/kr/posts/understanding-swift-
protocol/
[5] Swift 4.2 Protocol 공식 문서 정리 : https://
medium.com/@kimtaesoo188/swift-4-2-protocol-공식-문서-
정리-f3a97c6f8cc2
References
[6] 프로토콜 (Protocols) : https://jusung.gitbook.io/the-
swift-language-guide/language-guide/21-protocols
[7] 오늘의 Swift 상식 (Protocol) : https://medium.com/
@jgj455/오늘의-swift-상식-protocol-f18c82571dad
[8] [Swift] Protocol [01] : https://baked-
corn.tistory.com/24
[9] [Swift] Protocol [02] : https://baked-
corn.tistory.com/26
[10] Swift – 프로토콜 지향 프로그래밍 : https://
blog.yagom.net/531/
Thank you!

More Related Content

What's hot

일단 시작하는 코틀린
일단 시작하는 코틀린일단 시작하는 코틀린
일단 시작하는 코틀린Park JoongSoo
 
Javascript 실행 가능한 코드(Executable Code)와 실행 콘텍스트(Execution Context), Lexical En...
Javascript 실행 가능한 코드(Executable Code)와 실행 콘텍스트(Execution Context), Lexical En...Javascript 실행 가능한 코드(Executable Code)와 실행 콘텍스트(Execution Context), Lexical En...
Javascript 실행 가능한 코드(Executable Code)와 실행 콘텍스트(Execution Context), Lexical En...Young-Beom Rhee
 
7가지 동시성 모델 4장
7가지 동시성 모델 4장7가지 동시성 모델 4장
7가지 동시성 모델 4장HyeonSeok Choi
 
스위프트, 코틀린과 모던언어의 특징 (Swift, Kotlin and Modern Languages)
스위프트, 코틀린과 모던언어의 특징 (Swift, Kotlin and Modern Languages)스위프트, 코틀린과 모던언어의 특징 (Swift, Kotlin and Modern Languages)
스위프트, 코틀린과 모던언어의 특징 (Swift, Kotlin and Modern Languages)Yongha Yoo
 
프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oop프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oopYoung-Beom Rhee
 
Startup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JSStartup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JSCirculus
 
C++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threadsC++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threadsSeok-joon Yun
 
골때리는 자바스크립트 발표자료
골때리는 자바스크립트 발표자료골때리는 자바스크립트 발표자료
골때리는 자바스크립트 발표자료욱진 양
 
프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기Jongwook Choi
 
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 1. primitive
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 1. primitive[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 1. primitive
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 1. primitiveNAVER D2
 
7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍Hyunsoo Jung
 
C프로그래머를 위한 Java 기초 입문 (Java1.5 기준)
C프로그래머를 위한 Java 기초 입문 (Java1.5 기준)C프로그래머를 위한 Java 기초 입문 (Java1.5 기준)
C프로그래머를 위한 Java 기초 입문 (Java1.5 기준)혜웅 박
 
Javascript개발자의 눈으로 python 들여다보기
Javascript개발자의 눈으로 python 들여다보기Javascript개발자의 눈으로 python 들여다보기
Javascript개발자의 눈으로 python 들여다보기지수 윤
 
[2012 CodeEngn Conference 07] nesk - Defcon 20th : 본선 CTF 문제풀이
[2012 CodeEngn Conference 07] nesk - Defcon 20th : 본선 CTF 문제풀이[2012 CodeEngn Conference 07] nesk - Defcon 20th : 본선 CTF 문제풀이
[2012 CodeEngn Conference 07] nesk - Defcon 20th : 본선 CTF 문제풀이GangSeok Lee
 
[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)Bill Kim
 
[2009 CodeEngn Conference 03] hkpco - DEFCON CTF 2009 Binary Leetness 100-500...
[2009 CodeEngn Conference 03] hkpco - DEFCON CTF 2009 Binary Leetness 100-500...[2009 CodeEngn Conference 03] hkpco - DEFCON CTF 2009 Binary Leetness 100-500...
[2009 CodeEngn Conference 03] hkpco - DEFCON CTF 2009 Binary Leetness 100-500...GangSeok Lee
 
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로Jaeseung Ha
 
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)Kyoungchan Lee
 
스위프트 성능 이해하기
스위프트 성능 이해하기스위프트 성능 이해하기
스위프트 성능 이해하기Yongha Yoo
 

What's hot (20)

일단 시작하는 코틀린
일단 시작하는 코틀린일단 시작하는 코틀린
일단 시작하는 코틀린
 
Javascript 실행 가능한 코드(Executable Code)와 실행 콘텍스트(Execution Context), Lexical En...
Javascript 실행 가능한 코드(Executable Code)와 실행 콘텍스트(Execution Context), Lexical En...Javascript 실행 가능한 코드(Executable Code)와 실행 콘텍스트(Execution Context), Lexical En...
Javascript 실행 가능한 코드(Executable Code)와 실행 콘텍스트(Execution Context), Lexical En...
 
7가지 동시성 모델 4장
7가지 동시성 모델 4장7가지 동시성 모델 4장
7가지 동시성 모델 4장
 
스위프트, 코틀린과 모던언어의 특징 (Swift, Kotlin and Modern Languages)
스위프트, 코틀린과 모던언어의 특징 (Swift, Kotlin and Modern Languages)스위프트, 코틀린과 모던언어의 특징 (Swift, Kotlin and Modern Languages)
스위프트, 코틀린과 모던언어의 특징 (Swift, Kotlin and Modern Languages)
 
함수적 사고 2장
함수적 사고 2장함수적 사고 2장
함수적 사고 2장
 
프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oop프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oop
 
Startup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JSStartup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JS
 
C++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threadsC++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threads
 
골때리는 자바스크립트 발표자료
골때리는 자바스크립트 발표자료골때리는 자바스크립트 발표자료
골때리는 자바스크립트 발표자료
 
프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기
 
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 1. primitive
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 1. primitive[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 1. primitive
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 1. primitive
 
7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍
 
C프로그래머를 위한 Java 기초 입문 (Java1.5 기준)
C프로그래머를 위한 Java 기초 입문 (Java1.5 기준)C프로그래머를 위한 Java 기초 입문 (Java1.5 기준)
C프로그래머를 위한 Java 기초 입문 (Java1.5 기준)
 
Javascript개발자의 눈으로 python 들여다보기
Javascript개발자의 눈으로 python 들여다보기Javascript개발자의 눈으로 python 들여다보기
Javascript개발자의 눈으로 python 들여다보기
 
[2012 CodeEngn Conference 07] nesk - Defcon 20th : 본선 CTF 문제풀이
[2012 CodeEngn Conference 07] nesk - Defcon 20th : 본선 CTF 문제풀이[2012 CodeEngn Conference 07] nesk - Defcon 20th : 본선 CTF 문제풀이
[2012 CodeEngn Conference 07] nesk - Defcon 20th : 본선 CTF 문제풀이
 
[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)
 
[2009 CodeEngn Conference 03] hkpco - DEFCON CTF 2009 Binary Leetness 100-500...
[2009 CodeEngn Conference 03] hkpco - DEFCON CTF 2009 Binary Leetness 100-500...[2009 CodeEngn Conference 03] hkpco - DEFCON CTF 2009 Binary Leetness 100-500...
[2009 CodeEngn Conference 03] hkpco - DEFCON CTF 2009 Binary Leetness 100-500...
 
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
 
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
 
스위프트 성능 이해하기
스위프트 성능 이해하기스위프트 성능 이해하기
스위프트 성능 이해하기
 

Similar to [Swift] Protocol (2/2)

[Swift] Protocol (1/2)
[Swift] Protocol (1/2)[Swift] Protocol (1/2)
[Swift] Protocol (1/2)Bill Kim
 
읽기 좋은 코드가 좋은 코드다 Part one
읽기 좋은 코드가 좋은 코드다   Part one읽기 좋은 코드가 좋은 코드다   Part one
읽기 좋은 코드가 좋은 코드다 Part oneJi Hun Kim
 
Programming Cascading
Programming CascadingProgramming Cascading
Programming CascadingTaewook Eom
 
Realm은 어떻게 효율적인 데이터베이스를 만들었나?
Realm은 어떻게 효율적인 데이터베이스를 만들었나?Realm은 어떻게 효율적인 데이터베이스를 만들었나?
Realm은 어떻게 효율적인 데이터베이스를 만들었나?Leonardo YongUk Kim
 
포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++KWANGIL KIM
 
20150212 c++11 features used in crow
20150212 c++11 features used in crow20150212 c++11 features used in crow
20150212 c++11 features used in crowJaeseung Ha
 
Programming skills 1부
Programming skills 1부Programming skills 1부
Programming skills 1부JiHyung Lee
 
Lambda 란 무엇인가
Lambda 란 무엇인가Lambda 란 무엇인가
Lambda 란 무엇인가Vong Sik Kong
 
Effective c++(chapter 5,6)
Effective c++(chapter 5,6)Effective c++(chapter 5,6)
Effective c++(chapter 5,6)문익 장
 
세션1. block chain as a platform
세션1. block chain as a platform세션1. block chain as a platform
세션1. block chain as a platformJay JH Park
 
[113]how can realm_make_efficient_mobile_database
[113]how can realm_make_efficient_mobile_database[113]how can realm_make_efficient_mobile_database
[113]how can realm_make_efficient_mobile_databaseNAVER D2
 
나에 첫번째 자바8 람다식 지앤선
나에 첫번째 자바8 람다식   지앤선나에 첫번째 자바8 람다식   지앤선
나에 첫번째 자바8 람다식 지앤선daewon jeong
 
TR 069 클라이언트 검토자료 3편
TR 069 클라이언트 검토자료 3편TR 069 클라이언트 검토자료 3편
TR 069 클라이언트 검토자료 3편ymtech
 
Python Programming: Function
Python Programming: FunctionPython Programming: Function
Python Programming: FunctionChan Shik Lim
 
[2014 CodeEngn Conference 11] 이경식 - 동적 추적 프레임워크를 이용한 OS X 바이너리 분석
[2014 CodeEngn Conference 11] 이경식 - 동적 추적 프레임워크를 이용한 OS X 바이너리 분석[2014 CodeEngn Conference 11] 이경식 - 동적 추적 프레임워크를 이용한 OS X 바이너리 분석
[2014 CodeEngn Conference 11] 이경식 - 동적 추적 프레임워크를 이용한 OS X 바이너리 분석GangSeok Lee
 
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기Chris Ohk
 
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)Sang Don Kim
 
불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14 불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14 명신 김
 
Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉HyunJoon Park
 

Similar to [Swift] Protocol (2/2) (20)

[Swift] Protocol (1/2)
[Swift] Protocol (1/2)[Swift] Protocol (1/2)
[Swift] Protocol (1/2)
 
읽기 좋은 코드가 좋은 코드다 Part one
읽기 좋은 코드가 좋은 코드다   Part one읽기 좋은 코드가 좋은 코드다   Part one
읽기 좋은 코드가 좋은 코드다 Part one
 
Programming Cascading
Programming CascadingProgramming Cascading
Programming Cascading
 
Realm은 어떻게 효율적인 데이터베이스를 만들었나?
Realm은 어떻게 효율적인 데이터베이스를 만들었나?Realm은 어떻게 효율적인 데이터베이스를 만들었나?
Realm은 어떻게 효율적인 데이터베이스를 만들었나?
 
포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++
 
20150212 c++11 features used in crow
20150212 c++11 features used in crow20150212 c++11 features used in crow
20150212 c++11 features used in crow
 
Programming skills 1부
Programming skills 1부Programming skills 1부
Programming skills 1부
 
Lambda 란 무엇인가
Lambda 란 무엇인가Lambda 란 무엇인가
Lambda 란 무엇인가
 
Effective c++(chapter 5,6)
Effective c++(chapter 5,6)Effective c++(chapter 5,6)
Effective c++(chapter 5,6)
 
세션1. block chain as a platform
세션1. block chain as a platform세션1. block chain as a platform
세션1. block chain as a platform
 
[113]how can realm_make_efficient_mobile_database
[113]how can realm_make_efficient_mobile_database[113]how can realm_make_efficient_mobile_database
[113]how can realm_make_efficient_mobile_database
 
나에 첫번째 자바8 람다식 지앤선
나에 첫번째 자바8 람다식   지앤선나에 첫번째 자바8 람다식   지앤선
나에 첫번째 자바8 람다식 지앤선
 
TR 069 클라이언트 검토자료 3편
TR 069 클라이언트 검토자료 3편TR 069 클라이언트 검토자료 3편
TR 069 클라이언트 검토자료 3편
 
Python Programming: Function
Python Programming: FunctionPython Programming: Function
Python Programming: Function
 
[2014 CodeEngn Conference 11] 이경식 - 동적 추적 프레임워크를 이용한 OS X 바이너리 분석
[2014 CodeEngn Conference 11] 이경식 - 동적 추적 프레임워크를 이용한 OS X 바이너리 분석[2014 CodeEngn Conference 11] 이경식 - 동적 추적 프레임워크를 이용한 OS X 바이너리 분석
[2014 CodeEngn Conference 11] 이경식 - 동적 추적 프레임워크를 이용한 OS X 바이너리 분석
 
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
 
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
 
Java(3/4)
Java(3/4)Java(3/4)
Java(3/4)
 
불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14 불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14
 
Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉
 

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
 
[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
 
[Swift] Data Structure - Heap
[Swift] Data Structure - Heap[Swift] Data Structure - Heap
[Swift] Data Structure - HeapBill 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
 
[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] Data Structure - Heap
[Swift] Data Structure - Heap[Swift] Data Structure - Heap
[Swift] Data Structure - Heap
 

[Swift] Protocol (2/2)

  • 2. 목차 •Delegation •Adding Protocols Conformance with an Extension •Collections of Protocol Types •Protocol Inheritance •Class-Only Protocols •Protocol Composition •Optional Protocol Requirements •Protocol ExtensionsChecking for Protocol Conformance •References
  • 3. Delegation 위임(Delegation)은 클래스 혹은 구조체 인스턴스에 특정 행위에 대한 책임을 넘길 수 있게 해 주는 디자인 패턴 중 하나입니다. class Dice { } protocol DiceGame { var dice: Dice { get } func play() } // DiceGameDelegate에 선언해서 실제 DiceGame의 행위와 관련된 구현을 // DiceGameDelegate를 따르는 인스턴스에 위임합니다. protocol DiceGameDelegate: AnyObject { func gameDidStart(_ game: DiceGame) func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) func gameDidEnd(_ game: DiceGame) } class SnakesAndLadders: DiceGame { var dice: Dice = Dice() weak var delegate: DiceGameDelegate? func play() { delegate?.gameDidStart(self) } func end() { delegate?.gameDidEnd(self) } }
  • 4. Delegation class DiceGameTracker: DiceGameDelegate { var numberOfTurns = 0 func gameDidStart(_ game: DiceGame) { } func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) { } func gameDidEnd(_ game: DiceGame) { } } let tracker = DiceGameTracker() let game = SnakesAndLadders() game.delegate = tracker game.play()
  • 5. Adding Protocols Conformance with an Extension 이미 존재하는 타입에 새 프로토콜을 따르게 하기 위해 익스텐션을 사용할 수 있습니다. 원래 값에 접근 권한이 없어도 익스텐션을 사용해 기능을 확장할 수 있습니다. class Dice { let sides: Int init(sides: Int) { self.sides = sides } } protocol TextRepresentable { var textualDescription: String { get } } extension Dice: TextRepresentable { var textualDescription: String { return "A (sides)-sided dice" } } let d12 = Dice(sides: 12) print(d12.textualDescription) // Prints "A 12-sided dice"
  • 6. Adding Protocols Conformance with an Extension 만약 어떤 프로토콜을 충족에 필요한 모든 조건을 만족하지만 아직 그 프로토콜을 따른다는 선언을 하지 않았다면 그 선언을 빈 익스텐 션으로 선언할 수 있습니다. protocol TextRepresentable { var textualDescription: String { get } } struct Hamster { var name: String var textualDescription: String { return "A hamster named (name)" } } // Hamster 인스턴스인 simonTheHamster는 이제 TextRepresentable 타입으로 사용할 수 있습니다. extension Hamster: TextRepresentable {} let simonTheHamster = Hamster(name: "Simon") let somethingTextRepresentable: TextRepresentable = simonTheHamster print(somethingTextRepresentable.textualDescription) // A hamster named Simon
  • 7. Collections of Protocol Types 프로토콜을 Array, Dictionary등 Collection 타입에 넣기위한 타 입으로 사용할 수 있습니다. let d12 = Dice(sides: 12) let simonTheHamster = Hamster(name: "Simon") let things: [TextRepresentable] = [d12, simonTheHamster] for thing in things { print(thing.textualDescription) // A 12-sided dice // A hamster named Simon }
  • 8. Protocol Inheritance 클래스 상속같이 프로토콜도 상속할 수 있습니다. 여러 프로토콜을 상속받는 경우 콤마(,)로 구분합니다. protocol InheritingProtocol : SomeProtocol, AnotherProtocol { // protocol definition goes here } protocol PrettyTextRepresentable : TextRepresentable { var prettyTextualDescription: String { get } }
  • 9. Class-Only Protocols 구조체, 열거형에서 사용하지 않고 클래스 타입에만 사용가능한 프 로토콜을 선언하기 위해서는 프로토콜에 AnyObject를 추가합니 다. protocol SomeClassOnlyProtocol: AnyObject, SomeInheritedProtocol { // class-only protocol definition goes here }
  • 10. Protocol Composition 동시에 여러 프로토콜을 따르는 타입을 선언할 수 있습니다. protocol Named { var name: String { get } } protocol Aged { var age: Int { get } } struct Person: Named, Aged { var name: String var age: Int } func wishHappyBirthday(to celebrator: Named & Aged) { print("Happy birthday, (celebrator.name), you're (celebrator.age)!") } let birthdayPerson = Person(name: "Malcolm", age: 21) wishHappyBirthday(to: birthdayPerson) // Happy birthday, Malcolm, you're 21!
  • 11. Optional Protocol Requirements 프로토콜을 선언하면서 필수 구현이 아닌 선택적 구현 조건을 정의 할 수 있습니다. 이 프로토콜의 정의를 위해서 @objc 키워드를 프로토콜 앞에 붙이 고, 개별 함수 혹은 프로퍼티에는 @objc와 optional 키워드를 붙 입니다. @objc 프로토콜은 클래스 타입에서만 채용될 수 있고 구조체나 열 거형에서는 사용할 수 없습니다. @objc protocol CounterDataSource { @objc optional func increment(forCount count: Int) -> Int @objc optional var fixedIncrement: Int { get } }
  • 12. Protocol Extensions 익스텐션을 이용해 프로토콜을 확장할 수 있습니다. protocol RandomNumberGenerator { func random() -> Double } extension RandomNumberGenerator { func randomBool() -> Bool { return random() > 0.5 } } class LinearCongruentialGenerator: RandomNumberGenerator { var lastRandom = 42.0 let m = 139968.0 let a = 3877.0 let c = 29573.0 func random() -> Double { lastRandom = ((lastRandom * a + c).truncatingRemainder(dividingBy:m)) return lastRandom / m } } let generator = LinearCongruentialGenerator() print("Here's a random number: (generator.random())") // Prints "Here's a random number: 0.3746499199817101” print("And here's a random Boolean: (generator.randomBool())") // Prints "And here's a random Boolean: true"
  • 13. Protocol Extensions 프로토콜 익스텐션이 특정 조건에서만 적용되도록 선언할 수 있습니 다. 이 선언에는 where 절을 사용합니다. 다음은 Collection 엘리먼트가 Equatable인 경우에만 적용되는 allEqual()메소드를 구현한 예입니다. extension Collection where Element: Equatable { func allEqual() -> Bool { for element in self { if element != self.first { return false } } return true } } let equalNumbers = [100, 100, 100, 100, 100] let differentNumbers = [100, 100, 200, 100, 200] print(equalNumbers.allEqual()) // true print(differentNumbers.allEqual()) // false
  • 14. References [1] [Swift]Protocols 정리 : http://minsone.github.io/mac/ ios/swift-protocols-summary [2] Protocols : https://docs.swift.org/swift-book/ LanguageGuide/Protocols.html [3] Swift ) Protocols (4) : https://zeddios.tistory.com/347 [4] Swift Protocol 적재적소에 사용하기 : https:// academy.realm.io/kr/posts/understanding-swift- protocol/ [5] Swift 4.2 Protocol 공식 문서 정리 : https:// medium.com/@kimtaesoo188/swift-4-2-protocol-공식-문서- 정리-f3a97c6f8cc2
  • 15. References [6] 프로토콜 (Protocols) : https://jusung.gitbook.io/the- swift-language-guide/language-guide/21-protocols [7] 오늘의 Swift 상식 (Protocol) : https://medium.com/ @jgj455/오늘의-swift-상식-protocol-f18c82571dad [8] [Swift] Protocol [01] : https://baked- corn.tistory.com/24 [9] [Swift] Protocol [02] : https://baked- corn.tistory.com/26 [10] Swift – 프로토콜 지향 프로그래밍 : https:// blog.yagom.net/531/