SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Downloaden Sie, um offline zu lesen
SWIFT
Protocol (1/2)
Bill Kim(김정훈) | ibillkim@gmail.com
목차
•Protocols
•Protocol Syntax
•Property Requirements
•Method Requirements
•Initializer Requirements
•Protocols as Types
•References
Protocols
프로토콜은 특정 기능 수행에 필수적인 요수를 청의한 청사진
(blueprint)입니다.
프로토콜을 만족시키는 타입을 프로토콜을 따른다(conform)고 말
합니다.
프로토콜에 필수 구현을 추가하거나 추가적인 기능을 더하기 위해
프로토콜을 확장(extend)하는 것이 가능합니다.
출처: https://noahlogs.tistory.com/13 [인생의 로그캣]
Protocol Syntax
프로토콜의 정의는 클래스, 구조체, 열거형 등과 유사합니다.
protocol SomeProtocol {
// protocol definition goes here
}
struct SomeStructure: SomeProtocol {
// structure definition goes here
}
class SomeClass: SomeProtocol {
// class definition goes here
}
Property Requirements
프로토콜에서는 프로퍼티가 저장된 프로퍼티인지 계산된 프로퍼티
인지 명시하지 않습니다.
하지만 프로퍼티의 이름과 타입 그리고 gettable, settable한지
는 명시합니다. 필수 프로퍼티는 항상 var로 선언해야 합니다.
protocol SomeProtocol {
// 프로퍼티의 이름과 타입 그리고 gettable, settable한지는 명시합니다.
var mustBeSettable: Int { get set }
var doesNotNeedToBeSettable: Int { get }
}
protocol AnotherProtocol {
// 타입 프로퍼티는 static 키워드를 적어 선언합니다.
static var someTypeProperty: Int { get set }
}
Property Requirements
protocol FullyNamed {
// 하나의 프로퍼티를 갖는 프로토콜을 선언합니다.
var fullName: String { get }
}
struct Person: FullyNamed {
var fullName: String
}
let john = Person(fullName: "John Appleseed")
// john.fullName is "John Appleseed"
class Starship: FullyNamed {
var prefix: String?
var name: String
init(name: String, prefix: String? = nil) {
self.name = name
self.prefix = prefix
}
var fullName: String {
return (prefix != nil ? prefix! + " " : "") + name
}
}
// 계산된 프로퍼티로 사용될 수 있습니다.
var ncc1701 = Starship(name: "Enterprise", prefix: "USS")
// ncc1701.fullName is "USS Enterprise"
Method Requirements
익스텐션을 이용해 존재하는 타입에 새로운 이니셜라이저를 추가
할 수 있습니다.
이 방법으로 커스텀 타입의 이니셜라이저 파라미터를 넣을 수 있도
록 변경하거나 원래 구현에서 포함하지 않는 초기화 정보를 추가할
수 있습니다.
Method Requirements
protocol SomeProtocol {
static func someTypeMethod()
}
protocol RandomNumberGenerator {
func random() -> Double
}
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 another one: (generator.random())")
// Prints "And another one: 0.729023776863283"
Method Requirements
mutating 키워드를 사용해 인스턴스에서 변경 가능하다는 것을 표시할
수 있습니다.
이 mutating 키워드는 값타입 형에만 사용합니다.
protocol Togglable {
mutating func toggle()
}
enum OnOffSwitch: Togglable {
case off, on
mutating func toggle() {
switch self {
case .off:
self = .on
case .on:
self = .off
}
}
}
var lightSwitch = OnOffSwitch.off
lightSwitch.toggle()
print(lightSwitch) // lightSwitch is now equal to .on
Initializer Requirements
프로토콜에서 필수로 구현해야하는 이니셜라이저를 지정할 수 있습
니다.
protocol SomeProtocol {
init(someParameter: Int)
}
class SomeClass: SomeProtocol {
// 클래스에서 프로토콜 필수 이니셜라이저의 구현
// 프로토콜에서 특정 이니셜라이저가 필요하다고 명시했기 때문에 구현에서
// 해당 이니셜라이저에 required 키워드를 붙여줘야 합니다.
// 클래스 타입에서 final로 선언된 것에는 required를 표시하지 않도 됩니다.
// final로 선언되면 서브클래싱 되지 않기 때문입니다.
required init(someParameter: Int) {
// initializer implementation goes here
}
}
Initializer Requirements
protocol SomeProtocol {
init()
}
class SomeSuperClass {
init() {
// initializer implementation goes here
}
}
class SomeSubClass: SomeSuperClass, SomeProtocol {
// 특정 프로토콜의 필수 이니셜라이저를 구현하고, 수퍼클래스의 이니셜라이저를 서브클래싱하는 경우
// 이니셜라이저 앞에 required 키워드와 override 키워드를 적어줍니다.
required override init() {
// initializer implementation goes here
}
}
Protocols as Types
프로토콜도 하나의 타입으로 사용 가능합니다. 그렇기 때문에 다음
과 같이 타입 사용이 허용되는 모든 곳에 프로토콜을 사용할 수 있습
니다.
- 함수, 메소드, 이니셜라이저의 파라미터 타입 혹은 리턴 타입
- 상수, 변수, 프로퍼티의 타입
- 컨테이너인 배열, 사전 등의 아이템 타입
Protocols as Types
protocol RandomNumberGenerator {
func random() -> Double
}
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
}
}
class Dice {
let sides: Int
let generator: RandomNumberGenerator
init(sides: Int, generator: RandomNumberGenerator) {
self.sides = sides
self.generator = generator
}
func roll() -> Int {
return Int(generator.random() * Double(sides)) + 1
}
}
var d6 = Dice(sides: 6, generator: LinearCongruentialGenerator())
for _ in 1...5 {
rint("Random dice roll is (d6.roll())")
}
// Random dice roll is 3, Random dice roll is 5, Random dice roll is 4
// Random dice roll is 5, Random dice roll is 4
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!

Weitere ähnliche Inhalte

Was ist angesagt?

프론트엔드스터디 E04 js function
프론트엔드스터디 E04 js function프론트엔드스터디 E04 js function
프론트엔드스터디 E04 js functionYoung-Beom Rhee
 
프론트엔드스터디 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
 
이것이 자바다 Chap.11 기본 API 클래스(java)(KOR)
이것이 자바다 Chap.11 기본 API 클래스(java)(KOR)이것이 자바다 Chap.11 기본 API 클래스(java)(KOR)
이것이 자바다 Chap.11 기본 API 클래스(java)(KOR)MIN SEOK KOO
 
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
 
Javascript - Function
Javascript - FunctionJavascript - Function
Javascript - Functionwonmin lee
 
Lambda 란 무엇인가
Lambda 란 무엇인가Lambda 란 무엇인가
Lambda 란 무엇인가Vong Sik Kong
 
프론트엔드스터디 E03 - Javascript intro.
프론트엔드스터디 E03 - Javascript intro.프론트엔드스터디 E03 - Javascript intro.
프론트엔드스터디 E03 - Javascript intro.Young-Beom Rhee
 
이것이 자바다 Chap. 6 클래스(CLASS)(KOR)
이것이 자바다 Chap. 6 클래스(CLASS)(KOR)이것이 자바다 Chap. 6 클래스(CLASS)(KOR)
이것이 자바다 Chap. 6 클래스(CLASS)(KOR)MIN SEOK KOO
 
Startup JavaScript 6 - 함수, 스코프, 클로저
Startup JavaScript 6 - 함수, 스코프, 클로저Startup JavaScript 6 - 함수, 스코프, 클로저
Startup JavaScript 6 - 함수, 스코프, 클로저Circulus
 
호이스팅, 클로저, IIFE
호이스팅, 클로저, IIFE호이스팅, 클로저, IIFE
호이스팅, 클로저, IIFEChangHyeon Bae
 
Startup JavaScript 3 - 조건문, 반복문, 예외처리
Startup JavaScript 3 - 조건문, 반복문, 예외처리Startup JavaScript 3 - 조건문, 반복문, 예외처리
Startup JavaScript 3 - 조건문, 반복문, 예외처리Circulus
 
자바스크립트 기초문법~함수기초
자바스크립트 기초문법~함수기초자바스크립트 기초문법~함수기초
자바스크립트 기초문법~함수기초진수 정
 
이펙티브 C++ 공부
이펙티브 C++ 공부이펙티브 C++ 공부
이펙티브 C++ 공부quxn6
 
Start IoT with JavaScript - 5.객체2
Start IoT with JavaScript - 5.객체2Start IoT with JavaScript - 5.객체2
Start IoT with JavaScript - 5.객체2Park Jonggun
 
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
 
[Swift] Functions
[Swift] Functions[Swift] Functions
[Swift] FunctionsBill Kim
 
자바스크립트 함수
자바스크립트 함수자바스크립트 함수
자바스크립트 함수유진 변
 
Javascript 교육자료 pdf
Javascript 교육자료 pdfJavascript 교육자료 pdf
Javascript 교육자료 pdfHyosang Hong
 

Was ist angesagt? (20)

프론트엔드스터디 E04 js function
프론트엔드스터디 E04 js function프론트엔드스터디 E04 js function
프론트엔드스터디 E04 js function
 
프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oop프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oop
 
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
 
이것이 자바다 Chap.11 기본 API 클래스(java)(KOR)
이것이 자바다 Chap.11 기본 API 클래스(java)(KOR)이것이 자바다 Chap.11 기본 API 클래스(java)(KOR)
이것이 자바다 Chap.11 기본 API 클래스(java)(KOR)
 
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...
 
Javascript - Function
Javascript - FunctionJavascript - Function
Javascript - Function
 
Lambda 란 무엇인가
Lambda 란 무엇인가Lambda 란 무엇인가
Lambda 란 무엇인가
 
프론트엔드스터디 E03 - Javascript intro.
프론트엔드스터디 E03 - Javascript intro.프론트엔드스터디 E03 - Javascript intro.
프론트엔드스터디 E03 - Javascript intro.
 
이것이 자바다 Chap. 6 클래스(CLASS)(KOR)
이것이 자바다 Chap. 6 클래스(CLASS)(KOR)이것이 자바다 Chap. 6 클래스(CLASS)(KOR)
이것이 자바다 Chap. 6 클래스(CLASS)(KOR)
 
Startup JavaScript 6 - 함수, 스코프, 클로저
Startup JavaScript 6 - 함수, 스코프, 클로저Startup JavaScript 6 - 함수, 스코프, 클로저
Startup JavaScript 6 - 함수, 스코프, 클로저
 
호이스팅, 클로저, IIFE
호이스팅, 클로저, IIFE호이스팅, 클로저, IIFE
호이스팅, 클로저, IIFE
 
Startup JavaScript 3 - 조건문, 반복문, 예외처리
Startup JavaScript 3 - 조건문, 반복문, 예외처리Startup JavaScript 3 - 조건문, 반복문, 예외처리
Startup JavaScript 3 - 조건문, 반복문, 예외처리
 
자바스크립트 기초문법~함수기초
자바스크립트 기초문법~함수기초자바스크립트 기초문법~함수기초
자바스크립트 기초문법~함수기초
 
이펙티브 C++ 공부
이펙티브 C++ 공부이펙티브 C++ 공부
이펙티브 C++ 공부
 
Start IoT with JavaScript - 5.객체2
Start IoT with JavaScript - 5.객체2Start IoT with JavaScript - 5.객체2
Start IoT with JavaScript - 5.객체2
 
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
 
[Swift] Functions
[Swift] Functions[Swift] Functions
[Swift] Functions
 
javascript01
javascript01javascript01
javascript01
 
자바스크립트 함수
자바스크립트 함수자바스크립트 함수
자바스크립트 함수
 
Javascript 교육자료 pdf
Javascript 교육자료 pdfJavascript 교육자료 pdf
Javascript 교육자료 pdf
 

Ähnlich wie [Swift] Protocol (1/2)

[Swift] Protocol (2/2)
[Swift] Protocol (2/2)[Swift] Protocol (2/2)
[Swift] Protocol (2/2)Bill Kim
 
Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기jongho jeong
 
자바 8
자바 8자바 8
자바 8신 한
 
헷갈리는 자바스크립트 정리
헷갈리는 자바스크립트 정리헷갈리는 자바스크립트 정리
헷갈리는 자바스크립트 정리은숙 이
 
TR 069 클라이언트 검토자료 3편
TR 069 클라이언트 검토자료 3편TR 069 클라이언트 검토자료 3편
TR 069 클라이언트 검토자료 3편ymtech
 
PowerVR Low Level GLSL Optimisation
PowerVR Low Level GLSL Optimisation PowerVR Low Level GLSL Optimisation
PowerVR Low Level GLSL Optimisation 민웅 이
 
함수형 프로그래밍
함수형 프로그래밍함수형 프로그래밍
함수형 프로그래밍Min-su Kim
 
C Language I
C Language IC Language I
C Language ISuho Kwon
 
[아꿈사] The C++ Programming Language 13장 템플릿
[아꿈사] The C++ Programming Language 13장 템플릿[아꿈사] The C++ Programming Language 13장 템플릿
[아꿈사] The C++ Programming Language 13장 템플릿해강
 
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출GDG Korea
 
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
 
어플리케이션 성능 최적화 기법
어플리케이션 성능 최적화 기법어플리케이션 성능 최적화 기법
어플리케이션 성능 최적화 기법Daniel Kim
 
프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기Jongwook Choi
 
Refelction의 개념과 RTTR 라이브러리
Refelction의 개념과 RTTR 라이브러리Refelction의 개념과 RTTR 라이브러리
Refelction의 개념과 RTTR 라이브러리ssuser7c5a40
 
Programming Cascading
Programming CascadingProgramming Cascading
Programming CascadingTaewook Eom
 
Let's Go (golang)
Let's Go (golang)Let's Go (golang)
Let's Go (golang)상욱 송
 
[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?NAVER D2
 
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로Jaeseung Ha
 
20201121 코드 삼분지계
20201121 코드 삼분지계20201121 코드 삼분지계
20201121 코드 삼분지계Chiwon Song
 

Ähnlich wie [Swift] Protocol (1/2) (20)

[Swift] Protocol (2/2)
[Swift] Protocol (2/2)[Swift] Protocol (2/2)
[Swift] Protocol (2/2)
 
Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기
 
6 function
6 function6 function
6 function
 
자바 8
자바 8자바 8
자바 8
 
헷갈리는 자바스크립트 정리
헷갈리는 자바스크립트 정리헷갈리는 자바스크립트 정리
헷갈리는 자바스크립트 정리
 
TR 069 클라이언트 검토자료 3편
TR 069 클라이언트 검토자료 3편TR 069 클라이언트 검토자료 3편
TR 069 클라이언트 검토자료 3편
 
PowerVR Low Level GLSL Optimisation
PowerVR Low Level GLSL Optimisation PowerVR Low Level GLSL Optimisation
PowerVR Low Level GLSL Optimisation
 
함수형 프로그래밍
함수형 프로그래밍함수형 프로그래밍
함수형 프로그래밍
 
C Language I
C Language IC Language I
C Language I
 
[아꿈사] The C++ Programming Language 13장 템플릿
[아꿈사] The C++ Programming Language 13장 템플릿[아꿈사] The C++ Programming Language 13장 템플릿
[아꿈사] The C++ Programming Language 13장 템플릿
 
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출
 
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
 
어플리케이션 성능 최적화 기법
어플리케이션 성능 최적화 기법어플리케이션 성능 최적화 기법
어플리케이션 성능 최적화 기법
 
프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기
 
Refelction의 개념과 RTTR 라이브러리
Refelction의 개념과 RTTR 라이브러리Refelction의 개념과 RTTR 라이브러리
Refelction의 개념과 RTTR 라이브러리
 
Programming Cascading
Programming CascadingProgramming Cascading
Programming Cascading
 
Let's Go (golang)
Let's Go (golang)Let's Go (golang)
Let's Go (golang)
 
[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?
 
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
 
20201121 코드 삼분지계
20201121 코드 삼분지계20201121 코드 삼분지계
20201121 코드 삼분지계
 

Mehr von 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
 

Mehr von 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] Protocol (1/2)

  • 2. 목차 •Protocols •Protocol Syntax •Property Requirements •Method Requirements •Initializer Requirements •Protocols as Types •References
  • 3. Protocols 프로토콜은 특정 기능 수행에 필수적인 요수를 청의한 청사진 (blueprint)입니다. 프로토콜을 만족시키는 타입을 프로토콜을 따른다(conform)고 말 합니다. 프로토콜에 필수 구현을 추가하거나 추가적인 기능을 더하기 위해 프로토콜을 확장(extend)하는 것이 가능합니다. 출처: https://noahlogs.tistory.com/13 [인생의 로그캣]
  • 4. Protocol Syntax 프로토콜의 정의는 클래스, 구조체, 열거형 등과 유사합니다. protocol SomeProtocol { // protocol definition goes here } struct SomeStructure: SomeProtocol { // structure definition goes here } class SomeClass: SomeProtocol { // class definition goes here }
  • 5. Property Requirements 프로토콜에서는 프로퍼티가 저장된 프로퍼티인지 계산된 프로퍼티 인지 명시하지 않습니다. 하지만 프로퍼티의 이름과 타입 그리고 gettable, settable한지 는 명시합니다. 필수 프로퍼티는 항상 var로 선언해야 합니다. protocol SomeProtocol { // 프로퍼티의 이름과 타입 그리고 gettable, settable한지는 명시합니다. var mustBeSettable: Int { get set } var doesNotNeedToBeSettable: Int { get } } protocol AnotherProtocol { // 타입 프로퍼티는 static 키워드를 적어 선언합니다. static var someTypeProperty: Int { get set } }
  • 6. Property Requirements protocol FullyNamed { // 하나의 프로퍼티를 갖는 프로토콜을 선언합니다. var fullName: String { get } } struct Person: FullyNamed { var fullName: String } let john = Person(fullName: "John Appleseed") // john.fullName is "John Appleseed" class Starship: FullyNamed { var prefix: String? var name: String init(name: String, prefix: String? = nil) { self.name = name self.prefix = prefix } var fullName: String { return (prefix != nil ? prefix! + " " : "") + name } } // 계산된 프로퍼티로 사용될 수 있습니다. var ncc1701 = Starship(name: "Enterprise", prefix: "USS") // ncc1701.fullName is "USS Enterprise"
  • 7. Method Requirements 익스텐션을 이용해 존재하는 타입에 새로운 이니셜라이저를 추가 할 수 있습니다. 이 방법으로 커스텀 타입의 이니셜라이저 파라미터를 넣을 수 있도 록 변경하거나 원래 구현에서 포함하지 않는 초기화 정보를 추가할 수 있습니다.
  • 8. Method Requirements protocol SomeProtocol { static func someTypeMethod() } protocol RandomNumberGenerator { func random() -> Double } 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 another one: (generator.random())") // Prints "And another one: 0.729023776863283"
  • 9. Method Requirements mutating 키워드를 사용해 인스턴스에서 변경 가능하다는 것을 표시할 수 있습니다. 이 mutating 키워드는 값타입 형에만 사용합니다. protocol Togglable { mutating func toggle() } enum OnOffSwitch: Togglable { case off, on mutating func toggle() { switch self { case .off: self = .on case .on: self = .off } } } var lightSwitch = OnOffSwitch.off lightSwitch.toggle() print(lightSwitch) // lightSwitch is now equal to .on
  • 10. Initializer Requirements 프로토콜에서 필수로 구현해야하는 이니셜라이저를 지정할 수 있습 니다. protocol SomeProtocol { init(someParameter: Int) } class SomeClass: SomeProtocol { // 클래스에서 프로토콜 필수 이니셜라이저의 구현 // 프로토콜에서 특정 이니셜라이저가 필요하다고 명시했기 때문에 구현에서 // 해당 이니셜라이저에 required 키워드를 붙여줘야 합니다. // 클래스 타입에서 final로 선언된 것에는 required를 표시하지 않도 됩니다. // final로 선언되면 서브클래싱 되지 않기 때문입니다. required init(someParameter: Int) { // initializer implementation goes here } }
  • 11. Initializer Requirements protocol SomeProtocol { init() } class SomeSuperClass { init() { // initializer implementation goes here } } class SomeSubClass: SomeSuperClass, SomeProtocol { // 특정 프로토콜의 필수 이니셜라이저를 구현하고, 수퍼클래스의 이니셜라이저를 서브클래싱하는 경우 // 이니셜라이저 앞에 required 키워드와 override 키워드를 적어줍니다. required override init() { // initializer implementation goes here } }
  • 12. Protocols as Types 프로토콜도 하나의 타입으로 사용 가능합니다. 그렇기 때문에 다음 과 같이 타입 사용이 허용되는 모든 곳에 프로토콜을 사용할 수 있습 니다. - 함수, 메소드, 이니셜라이저의 파라미터 타입 혹은 리턴 타입 - 상수, 변수, 프로퍼티의 타입 - 컨테이너인 배열, 사전 등의 아이템 타입
  • 13. Protocols as Types protocol RandomNumberGenerator { func random() -> Double } 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 } } class Dice { let sides: Int let generator: RandomNumberGenerator init(sides: Int, generator: RandomNumberGenerator) { self.sides = sides self.generator = generator } func roll() -> Int { return Int(generator.random() * Double(sides)) + 1 } } var d6 = Dice(sides: 6, generator: LinearCongruentialGenerator()) for _ in 1...5 { rint("Random dice roll is (d6.roll())") } // Random dice roll is 3, Random dice roll is 5, Random dice roll is 4 // Random dice roll is 5, Random dice roll is 4
  • 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/