iOS Swift - Protocol

longlivedrgn·2022년 9월 6일
0

swift문법

목록 보기
17/36
post-thumbnail

Protocol Syntax

  • 먼저 protocol안에 method를 선언할 수 있지만, 메소드의 바디는 설정할 수 없다. 즉, 아래와 같이 protocol을 정의할 수 있다.
// 새로운 프로토콜을 선언하기
protocol Something {
    // 메소드 선언하기
    func doSomething()
}

Adopting Protocols

  • Protocol 채택한 struct 만들어보기.(메소드의 바디도 설정을 해줘야된다)
struct Size: Something {
    func doSomething() {
        print("Love")
    }
}

Class-Only Protocols

  • Class만이 채택할 수 있는 프로토콜을 만들기 -> AnyObject로 설정하기

아래와 같이 class만 채택할 수 있고, Something을 채택할 수 있는 프로토콜을 만들어보자

protocol SomethingObject: AnyObject, Something {
    
}

struct Value: SomethingObject {
    // 에러
}

class Object: SomethingObject {
    func doSomething() {
        <#code#>
    }
}

Property Requirements

  • 프로토콜에서는 항상 var로 property를 선언해야된다.
  • get과 set은 최소 만족 조건이다. 즉, get만 있으면 최소한 get(읽기)가능해야되며, get과 set이 둘다 있다면 읽고, 쓰기 둘다 가능해야된다.

기본 형식

protocol ProtocolName {
    var name: Type {get set}
    static var name: Type {get set}
}
  • 프로토콜을 한번 선언해보자
protocol Figure {
    var name: String { get }
}

위의 프로토콜은 get만을 선언하였기에 읽기만 가능해도 된다. 그리고 protocol 속 속성을 무조건 선언해줘야된다.
즉, 아래와 같은 struct들이 존재할 수 있다.

struct Rectangle: Figure {
    // get만 있기에 읽기만 가능해도 된다.
    let name = "Rect"
}

struct Triangle: Figure {
    var name = "Triangle"
}

struct Circle: Figure {
    var name: String {
        return "Circle"
    }
}
  • 그런데 만약 Figure protocol에 set을 추가한다면? 쓰는 것도 가능해야된다.
protocol Figure {
    var name: String { get set }
}
  • 따라서 위의 Retangle 과 Circle은 에러가 나게 된다.
  • 그리고 프로토콜의 속성에 static을 설정한다면?
protocol Figure {
    static var name: String { get set }
}
  • 그 프로토콜을 채택한 struct들의 변수에 다 static을 추가해줘야된다.

Method Requirements

  • 아래와 같이 protocol의 method는 body가 없기에 채택한 class나 struct가 자유자재로 body를 설정할 수 있다.
protocol Resettable {
    func reset()
}

class Size: Resettable {
    var width = 0.0
    var height = 0.0
    
    func reset() {
        width = 0.0
        height = 0.0
    }
}
  • 근데 만약 struct가 채택을 한다면, 그리고 그 안의 속성 값을 변경해야된다면 mutating을 protocol에도 struct에도 추가해주어야된다. 그리고 class는 상관없이 원래대로 채택하면 된다.
protocol Resettable {
    mutating func reset()
}


struct Size: Resettable {
    var width = 0.0
    var height = 0.0
    
    mutating func reset() {
        width = 0.0
        height = 0.0
    }
}

class Size: Resettable {
    var width = 0.0
    var height = 0.0
    
    func reset() {
        width = 0.0
        height = 0.0
    }
}
  • 또한 type method를 위하여 static을 추가해 줄 수 있다.
protocol Resettable {
    static func reset()
}

class Size: Resettable {
    var width = 0.0
    var height = 0.0
    
    func reset() {
        width = 0.0
        height = 0.0
    }
    
    static func reset() {
        
    }
}

Initializer Requirements

-> 이 파트는 다시 공부해보자

Subscript Requirements

  • get을 가지고 있다면
protocol List {
    subscript(idx: Int) -> Int {get}
}


struct DataStore: List {
    subscript(idx: Int) -> Int {
        return 0
    }
}
  • get과 set 둘 다 가지고 있다면?
protocol List {
    subscript(idx: Int) -> Int {get set}
}


struct DataStore: List {
    subscript(idx: Int) -> Int {
        get{
            return 0
        }
        set{
            
        }
    }
}
  • 근데 get과 set은 최소 만족 조건이기에 아래와 같은 코드도 가능하다.
protocol List {
    subscript(idx: Int) -> Int {get}
}


struct DataStore: List {
    subscript(idx: Int) -> Int {
        get{
            return 0
        }
        set{
            
        }
    }
}

0개의 댓글