공부한 것 꼭꼭 씹어먹기

protocol 본문

Swift 기초

protocol

젤라솜 2021. 10. 29. 20:51
반응형

프로토콜 : 특정 역할을 하기 위한 메서드, 프로퍼티, 기타 요구사항 등의 청사진을 정의하고 자신을 채택한 구조체, 클래스, 열거형에게 정의된 요구사항을 준수하라고 요청함 (🐣 프로토콜은 자바의 interface같은 것인가??)

protocol SomeProtocol {

}

protocol SomeProtocol2 {

}

// SomeStructure 구조체는 someProtocol, someProtocol2를 채택함
struct SomeStructure: SomeProtocol, SomeProtocol2 {

}

// 클래스는 상속받는 부모클래스가 있을 경우 가장 앞에 써줘야 함
class SomeClass: SomeSuperClass, SomeProtocol, SomeProtocol2 {}

protocol FirstProtocol {
	var name: Int { get set }
	var age: Int { get } // read only
}

protocol FullyNames {
	var fullName: String { get set }
	func printFullName() // 프로토콜에 함수를 정의할때 매개변수에 default를 설정할 수 없음
}

struct Person: FullyNames {
	var fullName: String // FullyNames에서 정의한 프로토콜을 준수해야한다
	func printFullName() {
		print(fullName) 
	}
}

// 생성자 요구사항 준수하기
protocol SomeProtocol5 {
	init()
}

class SomeClass: SomeProtocol5 {
  // class에서 생성자를 준수할때는 required를 써야한다(struct에서는 안써도 됨)
  // SomeClass가 상속받을수 없는 final class일때도 required를 안써도 된다
	required init() {  }   
}
반응형

'Swift 기초' 카테고리의 다른 글

옵셔널 체이닝  (0) 2021.10.30
extension  (0) 2021.10.30
타입캐스팅 : is, as  (0) 2021.10.28
상속  (0) 2021.10.27
property  (0) 2021.10.26
Comments