protocol 학습하기 (1) [ property, method, extension ]

2024. 8. 24. 21:53·Programing Langauge/swift
반응형

 

protocol이란 ?

프로토콜이란 반드시 구현해야하는 요구사항을 미리 정의하는 타입이다.

class, struct, enum, 심지어 protocol도 또다른 protocol을 채택할 수 있다.

 

참고
애플 공식문서

 

property 정의하기

먼저 property를 정의할 때 protocol에서 어떤식으로 요구사항을 정의하는 지 알아보자

 

1) var로 시작해서 변수명과 타입을 지정한다.

 

2) 연산 프로퍼티를 이용하여 `get`과 `set`의 역할을 부여한다.

 

3) get set일 경우 let property와 getter only computed property는 사용할 수 없다.

 

protocol SomeProtocol {
    
    var prop1: Int { get } // 읽기 전용
    var prop2: Int { get }
    var prop3: Int { get set }
    var prop4: Int { get set }
}

class SomeClass: SomeProtocol {
 
    var prop1: Int {
        return 1 // getter only
    }
    
    let prop2: Int = 1 // ✅ let은 set을 할 수 없으므로 getter only
    
    var prop3: Int = 3
    
    let prop4: Int = 4 // ❌ let은 set을 할 수 없으므로 불가
    
}

 

method 정의하기

property보다 훨씬 간단하다.

 

1) 메소드 명 , 매개변수, 리턴 타입을 지정해준다.

 

2) class를 제외한 struct와 enum에서 인스턴스 프로퍼티를 수정할 때는 mutating 키워드를 이용합니다.

 

protocol SomeProtocol {
   
    func f1(a: Int) -> Int
}

class SomeClass: someProtocol {
 
    func f1(a: Int) -> Int { return 1}
}

// ======================================================================================

protocol SomeProtocol {
   
    
    mutating func f2(n: Int)
}

struct SomeStruct : SomeProtocol {
    
    var prop1: Int = 0
    
    mutating func f2(n: Int) {
        prop1 = n
    }
    
}

 

protocol 확장

프로토콜을 확장하여 굳이 채택할 때마다 구현이 필요 없는 메서드를 기본적으로 구현하여 불필요한 구현을 방지한다.

 

protocol SomeProtocol {
    func defaultFunc() -> Int
}

extension SomeProtocol { // 확장 하여 기본 동작 구현
    func defaultFunc() -> Int {
        return 1
    }
}

struct SomeStruct: SomeProtocol {
    
    // 구현하지 않아도 에러 발생하지 않음 ✅
}

struct SomeStruct2: SomeProtocol {
    
    func defaultFunc() -> Int {
        return 2
    }
}

let ss = SomeStruct()
let ss2 = SomeStruct2()
print(ss.defaultFunc(), ss2.defaultFunc()) // 1 , 2

 

반응형

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

protocol 학습하기 (4) [ any, some ]  (1) 2024.08.25
protocol 학습하기 (3) [ associatedtype ]  (0) 2024.08.25
protocol 학습하기 (2) [ generic, 합성, 채택 체크 ]  (0) 2024.08.25
생성자  (1) 2024.08.24
class와 struct  (2) 2024.08.24
'Programing Langauge/swift' 카테고리의 다른 글
  • protocol 학습하기 (3) [ associatedtype ]
  • protocol 학습하기 (2) [ generic, 합성, 채택 체크 ]
  • 생성자
  • class와 struct
Hamp
Hamp
남들에게 보여주기 부끄러운 잡다한 글을 적어 나가는 자칭 기술 블로그입니다.
  • Hamp
    Hamp의 분리수거함
    Hamp
  • 전체
    오늘
    어제
    • 분류 전체보기 (304) N
      • CS (30)
        • 객체지향 (2)
        • Network (7)
        • OS (6)
        • 자료구조 (1)
        • LiveStreaming (3)
        • 이미지 (1)
        • 잡다한 질문 정리 (0)
        • Hardware (2)
        • 이론 (6)
        • 컴퓨터 그래픽스 (0)
      • Firebase (3)
      • Programing Langauge (37)
        • swift (32)
        • python (4)
        • Kotlin (1)
      • iOS (132)
        • UIKit (37)
        • Combine (1)
        • SwiftUI (32)
        • Framework (7)
        • Swift Concurrency (22)
        • Tuist (6)
        • Setting (11)
        • 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 (13) N
        • 어노테이션 (1)
        • 튜토리얼 (11) N
      • CI-CD (4)
      • Android (0)
        • Jetpack Compose (0)
  • 블로그 메뉴

    • 홈
    • 태그
  • 링크

  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

  • 반응형
  • hELLO· Designed By정상우.v4.10.0
Hamp
protocol 학습하기 (1) [ property, method, extension ]
상단으로

티스토리툴바