Swift
Swift - protocol(프로토콜)
leebean
2021. 11. 3. 13:14
(인덕대학교 컴퓨터소프트웨어학과 iOS프로그래밍기초(21-2학기)한성현 교수님 강의 내용을 변형 및 요약 했습니다.)
protocol(프로토콜)
- 특정 클래스와 관련없는 함수(메서드)들의 선언의 집합입니다.
- 이름은 다르지만 protocol과 같은 기능을 가지고 있는 언어가 있습니다.
-
언어 명칭 JAVA interface C# interface C++ abstract Oriented class Swift protocol
-
- protocol 정의
-
protocol <프로토콜명>{ 프로퍼티명 메서드 선언 //선언만 합니다 }
-
- protocol 상속
-
protocol <프로토콜 명> : <부모1 프로토콜>, <부모2 프로토콜>{ //프로토콜은 다중상속이 가능합니다. }
-
(protocol 프로퍼티 / 메서드 선언 예제 코드)
protocol sample {
var readwrite :Int {get set }//읽기 쓰기 전용입니다.
var read :Int {get }//읽기 전용입니다.
static var readwrite2 :Int {get set }
static func Method ()
func rand ()->Double
}
(protocol 정의, 채택, 준수 예제 코드)
protocol Jumping {//대리하고 싶은 함수 목록을 작성합니다.
var ready :Int {get set }//읽기와 쓰기 가능한 프로퍼티입니다.
func jump ()//메서드 선언만 해야합니다.
//JAVA언어의 interface와 비슷한 기능을 합니다.
}
class woMan : Jumping {//채택, adopt
var ready :Int = 10 //준수, conform
func jump (){ //준수, conform
print ("점핑!")
}
//채택과 준수를 안할 경우 adopt,conform을 해야한다는
//에러메세지가 나옵니다.
}
class cat : Jumping {//채택, adopt
var ready :Int = 20 //준수, conform
func jump (){ //준수, conform
print ("낮은 점핑!")
}
}
let kim = woMan ()
let short = cat ()
print (kim.ready )//10이 출력됩니다.
print (short.ready )//20이 출력됩니다.
kim.jump ()//점핑! 이 출력됩니다.
short.jump ()//낮은 점핑! 이 출력됩니다.