Day 11 : 프로토콜 & 익스텐션

sun·2021년 9월 18일
0

100 Days of SwiftUI

목록 보기
6/11

[Day 11]

@ Day 11

# 프로토콜

  • 프로토콜을 통해 어떤 역할이 가져야 할 프로퍼티와 메서드를 지정할 수 있음
  • 단, 요소를 정의할 뿐 구체적인 코드(구현 방식)를 포함하지는 않음
  • 프로퍼티를 요구하는 경우 반드시 var 키워드를 사용하며, 용도를 { get } 혹은 { get set } 으로 표기해야 함
  • 어떠한 타입이 특정 프로토콜을 채택(Accept)해서 모든 요구사항을 충족하는 경우 해당 프로토콜을 준수(Conform)한다고 함
protocol Purchaseable {
    var name: String { get set }
}

struct Book: Purchaseable {  // Purchaseable 프로토콜 채택
    var name: String  // 프로토콜에서 요구한 프로퍼티 (프로토콜 준수)
    var author : String  // 그 외에 해당 구조체만의 프로퍼티도 추가 가능
}

struct Coffee: Purchaseable {
    var name: String
    var strength: Int
}

func buy(_ item: Purchaseable) {
    print("I'm buying \(item.name)")
}

var harryPotter = Book(name: "Harry Potter", author: "J. K. Rowling")
var espresso = Coffee(name: "espresso", strength: 10)

buy(harryPotter)  // I'm buying Harry Potter
buy(espresso)  // I'm buying espresso

# 프로토콜 상속

  • 클래스와 달리 다중 상속 가능
protocol Payable {
    func calculateWages() -> Int
}

protocol NeedsTraining {
    func study()
}

protocol HasVacation {
    func takeVacation(days: Int)
}

protocol Employee: Payable, NeedsTraining, HasVacation {}  // 다중 상속

# 익스텐션(Extensions)

  • extension 을 통해 이미 있는 타입에 메서드를 추가해서 funtionality 를 증진시킬 수 있음
  • stored property 는 추가할 수 없으며 computed property 만 추가 가능
extension Int {
    var isEven: Bool {
        return self % 2 == 0  // 여기서 self 는 Int 
    }
    
    func squared() -> Int {
        return self * self
    }
}

# 프로토콜 익스텐션

  • 프로토콜 익스텐션을 통해 특정 프로토콜을 준수하는 모든 타입이 특정 프로퍼티/메서드 구현 방식을 따르도록 할 수 있음
  • 즉, 프로토콜의 디폴트 구현 방식 을 지정할 수 있음
let pythons = ["Eric", "Graham", "John", "Michael", "Terry", "Terry"]
let beatles = Set(["John", "Paul", "George", "Ringo"])

extension Collection {  // 배열과 세트는 모두 Collection 프로토콜 준수
    func summarize() {
        print("There are \(count) of us:")
        
        for name in self {
            print(name)
        }
    }
}

pythons.summarize()
beatles.summarize()

# 프로토콜 지향 프로그래밍(Protocol-oriented programming)

  • 프로토콜과 프로토콜 익스텐션을 기반으로 코드를 작성하는 프로그래밍 방식
protocol Identifiable {
    var id: String { get set }
    func identify()
}

extension Identifiable { // 프로토콜이 요구하는 identify() 메서드의 디폴트 지정
    func identify() {
        print("My id is \(id).")
    }
}

struct User: Identifiable {
    var id: String
}

let sun = User(id: "sun")
sun.identify()  // My id is sun.

☀️ 느낀점

  • 그동안은 별 생각 없이 변수를 선언할 때 var name: String 과 같이 타입을 지정했는데 오늘 배우고 나니 타입 또한 프로토콜 익스텐션 으로 구현된 거라 이런식으로 타입을 지정하는구나 하는 생각이 들었다...!
profile
☀️

0개의 댓글