본문 바로가기
iOS_Swift/2022_Summer

Swift - Protocol(프로토콜)

by chozjjae 2022. 8. 11.

Protocol, 프로토콜 이란 ?

Swift에서 특정역할을 하기 위한 프로퍼티, 메서드, 기타 요구사항 등을 미리 선언만 해둔 문법을 의미 합니다.

 

protocol과 상속의 차이점

  • 클래스끼리는 상속, protocol은 채택 되었다고 표현합니다.
  • protocol은 여러개를 채택할 수 있습니다.
  • class(클래스), struct(구조체) 모두 채택 가능합니다.

protocol의 간단 예제1

aprotocol과 bprotocol생성

aprotocol - 저장 프로퍼티 선언

bprotocol - 타입 프로퍼티 선언

그 후 struct에서 aprotocol 채택

import UIKit

protocol aprotocol{
    var name : String{get} //읽기전용 프로퍼티
    var age : Int{get set} //읽기, 쓰기 모두 가능
}

protocol bprotocol{
    static var someprotocol : Int{get set}
} //타입 프로퍼티 선언

struct teststruct:aprotocol{
    var name : String
    var age : Int
}

protocol 간단 예제2

메서드를 정의할 때 메서드의 필요한 매개변수는 정의 해야한다. but 매개변수의 default 값은 정의 할 수 없다.

import UIKit

protocol aprotocol{
    var name : String{get} //읽기전용 프로퍼티
    var age : Int{get set} //읽기, 쓰기 모두 가능
    func printprotocol() //
}

protocol bprotocol{
    static var someprotocol : Int{get set}
} //타입 프로퍼티 선언

struct teststruct:aprotocol{
    var name : String = "cho"
    var age : Int = 25
    func printprotocol() {
        print(name, age)
    }
}
var cho = teststruct()
cho.printprotocol()


protocol 간단 예제3

init() 생성자 채택 받기

  • class 에서 init() 생성자를 채택 받으려면 required를 꼭 붙여줘야한다.
    • required initializer - 자식 클래스에서 반드시 required 키워드로 재 작성해야하는 initializer입니다.
  • struct(구조체)에서는 상관 없다.
protocol cprotocol{
    init() //생성자 init()도 protocol로 채택 가능하다.
}

class cclass: cprotocol{
    required init(){
        
    }
}

 

 


참조 - 패스트 캠퍼스의 "30개 프로젝트로 배우는 iOS 앱 개발 with Swift 초격차 패키지 Online." 강의

'iOS_Swift > 2022_Summer' 카테고리의 다른 글

Swift - enum(열거형)  (0) 2022.08.15
Swift - extension(익스텐션)  (0) 2022.08.12
Swift - if, guard  (0) 2022.08.10
Swift - assert  (0) 2022.08.10
Swift - 타입 캐스팅(is, as)  (0) 2022.08.09