Trulyawesome

[Swift] Protocol 본문

프로그래밍/iOS

[Swift] Protocol

ethkelitt 2020. 9. 24. 21:47

Protocol

프로토콜은 메소드나 속성, 특정 작업 기능의 부분에 맞는 요구 사항의 청사진을 정의합니다.프로토콜은 메소드나 속성의 직접적인 구현을 제공하지 않습니다. 프로토콜은 이 기능의 실제 구현을 제공하기 위한 클래스, 구조체, 열거형에 적용됩니다.


Syntax(문법)

protocol SomeProtocol {
  //protocol definition
}

적용은 이렇게 합니다

class VC: UIViewController,SomeProtocol {
  //method구현
}

Property Requirement(속성 요구사항)

var 키워드를 사용하여 변수 property로 정의합니다 {get set} 을 사용합니다

protocol SomeProtocol {
  var aProperty: String { get }
  var bProperty: String { get set }
}

읽기 전용 프로퍼티는 get을 사용하고 읽기,쓰기 프로퍼티는 {get set} 을 사용합니다


클래스 전용 프로토콜

protocol SomeProtocol: class {} //구조체와 열거형에서 채택시 에러발생

위와 같이 클래스에서만 채택가능하게 프로토콜을 만들 수 있습니다. 열거형이나 구조체에 적용하면 에러가 발생합니다.