Open Do-hyun-Kim opened 12 months ago
,
로 구분한다.var
)로 선언되어야 한다.protocol Algorithm {
var bfs: String { get set }
var dp: String { get set }
var math: String { get set }
func test()
}
class company: Algorithm {
var bfs: String = "Gold"
var dp: String = "Sliver"
var math: String = "Bronze"
func test() {
print("테스트 통과!")
}
}
@objc
를 붙여서 optional로 선언한다@objc
는 Objective-C에서 사용될 수 있다는 뜻으로, Objective-C에서 프로토콜은 클래스에서만 채택 가능하기때문에 @objc
가 붙으면 자동으로 AnyObject로 채택된다.@objc protocol Algorithm: AnyObject {
var dp: String { get set }
@objc optional var bfs: String { get set }
}
class company: Algorithm {
var dp: String = "Gold"
var bfs: String = "Silver"
func test() {
print("테스트 통과!")
}
}
let aCompany: Algorithm = company.init()
aCompany.dp // Gold
aCompany.bfs // Sliver
그 프로토콜을 준수한다(Confirm)
라고 표현함protocol 프로토콜 이름 {
프로토콜 정의
}
구조체, 클래스, 열거형 등에서 프로토콜을 채택하려면 타입 이름 뒤에 콜론(:)을 붙여준 후 채택할 프로토콜 이름을 쉼표(,)로 구분하여 명시함
struct SomeStruct: AProtocol, AnotherProtocol {
// 구조체 정의
}
class SomeClass: AProtocol, AnotherProtocol {
// 클래스 정의
}
enum SomeEnum: AProtocol, AnotherProtocol {
// 열거형 정의
}
만약, 클래스가 다른 클래스를 상속받는다면 상속받을 클래스 이름 다음에 채택할 프로토콜을 나열
class SomeClass: SuperClass, AProtocol, AnotherProtocol {
// 클래스 정의
}
protocol AProtocol{
var a: String{ get set }
// AProtocol에 정의된 a는 읽기와 쓰기 모두를 요구했고
var b: String{ get }
// b는 읽기만 가능하다면 어떻게 구현되어도 상관 없다는 요구사항임
}
protocol BProtocol{
// 타입 프로퍼티를 요구하려면 static 키워드를 사용함.
// 클래스의 타입 프로퍼티에는 상속 가능한 타입 프로퍼티인 class 타입 프로퍼티와
// 상속 불가능한 static 타입 프로퍼티가 있으나!
// 이 두 타입 프로퍼티를 따로 구분하지 않고 static 키워드를 사용하여 프로퍼티를 요구하면 됨
static var c: Int { get set }
static var d: Int { get }
// c, d 모두 타입 프로퍼티 요구하는 중
}
protocol Talkable {
var topic: String { get set }
// 이 프로토콜은 어떤 주제에 말할 수 있게 하는 프로퍼티인 topic 을 요구함
}
struct person: Talkable {
var topic: String
// 그래서 위 프로토콜을 채택하여 준수하는 Person 클래스는 topic 프로퍼티를 가져야함
}
protocol Talkable {
var topic: String { get set }
func talk(to: person)
//프로토콜이 요구할 메서드는 프로토콜 정의에서 작성,
//다만 실제 구현부인 중괄호({}) 부분은 제외하고 메서드의 이름, 매개변수, 반환 타입 등만 작성함
//그리고 매개변수 기본값을 지정할 수 없음
//static 키워드를 사용하여 요구한 타입 메서드를 클래스에서 실제 구현할 대에는 static 키워드나
//class 키워드 어느 쪽을 사용해도 무방함
}
struct person: Talkable {
func talk(to: person) {
print("\(topic)에 대히 \(to.name)에게 이야기합니다.")
}//
var topic: String
var name: String
}
protocol Talkable {
var topic: String { get set }
func talk(to: Person)
init(name: String, topic: String)// 정의는 하지만 구현은 X, 매개변수만
}
struct Person: Talkable {
var topic: String
var name: String
func talk(to: Person){
print("\(topic)에 대해 \(to.name)에게 이야기합니다.")
}
init(name: String, topic: String) {
self.name = name
self.topic = topic
}
}
let cat: Person = Person(name: "고양이", topic: "집사")
let sister: Person = Person(name: "언니", topic: "가족")
cat.talk(to: sister)// -> 집사에 대해 언니에게 이야기합니다.
protocol Readable {
func read()
}
protocol Writeable {
func write()
}
protocol ReadSpeakable: Readable {
func speak() //상속
}
protocol ReadWriteSpeakable: Readable, Writeable {
func speak() // 상속의 상속
}
class SomeClass: ReadWriteSpeakable {
func read() {
print("Read")
}
func write() {
print("Write")
}
func speak() {
print("Speak")
}
}
하나 이상의 프로토콜을 상속받고, 기존 프로토콜의 요구사항보다 더 많은 요구사항을 추가할 수 있음
protocol
키워드를 이용하여 선언되며, 구조체나 클래스가 반드시 포함해야 하는 메서드와 프로퍼티를 정의한다. protocol A {
var variable: Int { get set } // getter or getter/setter 를 명시해 줘야한다.
func A()
}
protocol B {
...
}
protocol C {
...
}
protocol A: B, C {
var variable: Int { get set }
func A()
}
protocol A {
var variableA: Int { get set }
func A()
}
extension A {
var variableA: Int {
return 10
}
func A() {
print(variableA)
}
}
protocol A {
associatedtype Element
var variableA: Element { get set }
func A() -> Element
}
프로토콜이란 무엇인지 설명하시오.
Protocol 이란
Method
,Property
등 기타 요구사항등을 정의하는 청사진 이다.struct
,class
,enum
은protocol
을 채택하여 요구사항을 구현한다.Protocol
에서 내부 기능까지 구현하고 싶다면extension
을 활용하여 로직을 구현하여protocol
을 활용할 수 있다.Property Requirements 정의
protocol
에서는 저장 프로퍼티(Stored Property)
인지 연산 프로퍼티(Computed Property
) 인지 명시 하지 않는다.Property
를 정의할때 이름(Name), 타입(Type), 그리고getter
,setter
인지 명시한다.Property
를 명시할때는 항상var
변수로 선언한다.Property
는 저장 프로퍼티(Stored Property
), 연산 프로퍼티(Computed Property
) 둘다 사용해서 구현 할 수 있다.Method Requirements 정의
protocol
에서는 인스턴스 메소드(instance Method
) , 타입 메소드(type Method
)를 정의 할 수 있다.protocol
내에서 사용 할 수없다.{}
는 적지 않는다.class
Type Method 는protocol
내에서 정의 할 수 없으며static
타입 메서드를 정의 후 구현부에서 변경하여야 한다.mutating
키워드를 사용하여 인스턴스에서 변경 가능하다는 것을 표시할 수 있으며 값 타입 (struct
,enum
)에서만 사용이 가능하다.Initializer Requirements 정의
protocol
은 초기화(Initializer
) 도 정의가 가능하다.prtocol
을 채택한class
는 Initializer에required
키워드를 붙여줘야 한며SuperClass
의 Initializer를SubClass
에 상속하는 경우SubClass
의 Initializer 앞에required
키워드와override
키워드를 붙여줘야 한다.struct
같은 경우 상속이 없기 때문에required
키워드를 붙여주지 않아도 된다.간혹
UICollectionViewCell
,UITableViewCell
required Initializer
를 붙여주는 이유는 UICollectionViewCell, UITableViewCell이UIView, UIScrollView
를 상속 받고 있으며, 이 두가지 객체가NSCoding
프로토콜을 채택하고 있기에 정의 해야 한다.Protocol Composition 정의
Super Class
를 지정하는데 사용할 수 있는 클래스 타입이 포함 될수 있다.Protocol 다양한 활용
protocol
에AnyObject
를 채택함으로써 클래스 전용 프로토콜로 제한 할 수있다.extension
을 활용하여protocol
정의된Method
내부 로직을 구현 할 수 있다.protocol
을 통해`Delegate Pattern
을 구현 하여 책임을 다른 객체에게 위임 할 수 있다.Value Type
같은 상속이 없는 단점을protocol
을 활용하여 수평적 확장이 가능하다.📝 참고 사이트