protocol 학습하기 (2) [ generic, 합성, 채택 체크 ]

2024. 8. 25. 15:19·Programing Langauge/swift
반응형

 

프로토콜에 제네릭 및 제약조건 적용하기

제네릭 (범용 타입)은 런타임 시 타입을 결정하게하여 함수 또는 변수에 상황에 맞는 타입을
사용할 수 있게하는 기능이다.
제네릭 역시 프로토콜에 적용 할 수 있으며, 프로토콜 타입을  재네릭으로 사용할 수 있다.

 

1) 프로토콜에 제네릭 사용하기 

기본 제네릭 패턴 또는 where과 조합해서 쓸 수 있다.

protocol SomeProtocol {
    
    func f1<T: Equatable>(param: T) // 단순 제네릭 이용
    

    func f2<T>(param: T) where T: Equatable // 제네릭 + where 이용
    
}

 

2) 제네릭에 프로토콜 타입으로 사용하기

프로토콜 역시 제네릭 타입으로 사용할 수 있다.

protocol SomeProtocol {
    
    func someFunc() -> Void
}

class SomeClass: SomeProtocol {
    func someFunc() {}
}

func genericFunc<T: SomeProtocol>(generic: T) -> Void {
    generic.someFunc()
}

func genericFunc2<T>(generic: T) -> Void where T: SomeProtocol {
    generic.someFunc()
}

 


프로토콜 합성 

여러가지 프로토콜을 모두 만족해야할 때 & 연산자를  사용해서 표시한다.

가장 대표적인 프로토콜로는 Codable  프로토콜이 생각난다.

 

Codable = Decodable + Encodable 인 형태이다. 한번 진짜 그런지 확인해보자.

아래에서 보다시피 Codable은 새로운 프로토콜이 아닌 단순 Decodable 과 Encodable이 합성된 typealias이다.

Codable

프로토콜 선언 시 다음과 같이 사용할 수 도 있다.

 

protocol SomeProtocol {
    
    func someFunc() -> Void
}

protocol SomeProtocol2 {
    func someFunc2() -> Void
}

protocol SomeProtocol3:  SomeProtocol & SomeProtocol2 {
    func someFunc3() -> Void
}


class SomeClass: SomeProtocol3 {
    
    func someFunc() {}
    
    func someFunc2() {}
    
    func someFunc3() {}
    
}

프로토콜 채택 체크 

프로토콜은 체크 여부는 is, as , where을 통해 할 수 있다.

 

1) is 

프로토콜을 준수하면 true 아니면 false 

protocol SomeProtocol {
    
    func someFunc() -> Void
}

class SomeClass: SomeProtocol {
    func someFunc() {}
}

var someC = SomeClass()

if someC is SomeProtocol {
    print("Some Class confirmed SomeProtocol") // ✅
} else {
    print("Some Class doesn't confirmed SomeProtocol ") ❌
}

2) as

as는 구현체의 타입을 프로토콜 타입으로 변환한다.

as? 는 채택하지 않았을 경우 nil을 리턴 as!는 런타임 에러를 발생시킵니다.

 

guard let p = someC as? SomeProtocol else {
    fatalError()
}

let pp = someC as! SomeProtocol

 

3) where

where은 크게 2가지 역할을 한다.

첫번 째는 특정 패턴과 조합하여 조건을 추가할 수 있고 두번 째는  재네릭 타입에 대한 제약을 추가할 수 있다.

우리는 프로토콜에 대한 사용을 배우고 있으므로 두번 째 역할을 이용한다.

 

func genericFunc2<T>(generic: T) -> Void where T: SomeProtocol {
    generic.someFunc()
}
반응형

'Programing Langauge > swift' 카테고리의 다른 글

protocol 학습하기 (4) [ any, some ]  (1) 2024.08.25
protocol 학습하기 (3) [ associatedtype ]  (0) 2024.08.25
protocol 학습하기 (1) [ property, method, extension ]  (1) 2024.08.24
생성자  (1) 2024.08.24
class와 struct  (2) 2024.08.24
'Programing Langauge/swift' 카테고리의 다른 글
  • protocol 학습하기 (4) [ any, some ]
  • protocol 학습하기 (3) [ associatedtype ]
  • protocol 학습하기 (1) [ property, method, extension ]
  • 생성자
Hamp
Hamp
남들에게 보여주기 부끄러운 잡다한 글을 적어 나가는 자칭 기술 블로그입니다.
  • Hamp
    Hamp의 분리수거함
    Hamp
  • 전체
    오늘
    어제
    • 분류 전체보기 (297)
      • CS (29)
        • 객체지향 (2)
        • Network (7)
        • OS (6)
        • 자료구조 (1)
        • LiveStreaming (3)
        • 이미지 (1)
        • 잡다한 질문 정리 (0)
        • Hardware (2)
        • 이론 (5)
        • 컴퓨터 그래픽스 (0)
      • Firebase (3)
      • Programing Langauge (36)
        • swift (31)
        • python (4)
        • Kotlin (1)
      • iOS (131)
        • UIKit (37)
        • Combine (1)
        • SwiftUI (32)
        • Framework (7)
        • Swift Concurrency (22)
        • Tuist (6)
        • Setting (10)
        • Modularization (1)
        • Instruments (6)
      • PS (59)
        • 프로그래머스 (24)
        • 백준 (13)
        • LeetCode (19)
        • 알고리즘 (3)
      • Git (18)
        • 명령어 (4)
        • 이론 (2)
        • hooks (1)
        • config (2)
        • action (7)
      • Shell Script (2)
      • Linux (6)
        • 명령어 (5)
      • Spring (9)
      • CI-CD (4)
      • Android (0)
        • Jetpack Compose (0)
  • 블로그 메뉴

    • 홈
    • 태그
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    CS
    프로그래머스
    투포인터
    SwiftUI
    Network
    IOS
    dp
    Tuist
    boostcamp
    백준
    lifecycle
    GIT
    dfs
    Swift
    UIKit
    concurrency
    dispatch
    protocol
    property
    AVFoundation
  • 최근 댓글

  • 최근 글

  • 반응형
  • hELLO· Designed By정상우.v4.10.0
Hamp
protocol 학습하기 (2) [ generic, 합성, 채택 체크 ]
상단으로

티스토리툴바