[Swift] 프로토콜(Protocol)이란?

728x90

프로토콜(Protocol)이란?


  • 형식에서 제공하는 멤버 목록

  • 프로토콜에 선언 되어있는 필 수 멤버를 모두 구현해야 한다(프로토콜을 채용한다)

  • Protocols

    protocol protocolName {
      propertyRequirements
      methodRequirements
      initializerRequirements
      subscriptRequirements
    }
    
    protocol ProtocolName: Protocol, ... {
    
    }
    

 

  • Adopting Protocols

    enum TypeName : ProtocolName, ... {
    
    }
    struct TypeName : ProtocolName, ... {
    
    }
    class TypeName : SuperClass, ProtocolName, ... {
    
    }
  • Class-Only Protocols

    protocol ProtocolName: AnyObject {
    
    }
  • Property Requirements

    protocol ProtocolName {
        var name: Type { get set }
        static var name: Type { get set }
    }
  • Method Requirements

    protocol ProtocolName {
      func name(param) -> ReturnType
      static func name(param) -> ReturnType
      mutating func name(param) -> ReturnType
    }
  • Initializer Requirements

    protocol ProtocolName {
      init(param)
      init?(param)
      init!(param)
    }
  • Subscript Requirements

    protocol ProtocolName {
      subscript(param) -> ReturnType { get set }
    }

코드(예시) & 설명


import UIKit

//이 프로토콜을 채용하는 구조체는 doSomething 메소드를 사용해야만 한다
protocol Something {
    func doSomething()
}

struct Size: Something {
    func doSomething() {

    }
}

//------------------------------------------------------------

protocol SomethingObject: AnyObject, Something {

}

class Value: SomethingObject {
    func doSomething() {

    }
}

protocol Figure {
    static var name: String { get set } //모든 속성을 형식 선언으로 해야 한다.
}

struct Rectangle: Figure {
   static var name = "Rect"
}

struct Triangle : Figure {
   static var name = "Triangle" //최소 요건이기때문에 읽기 전용이 아니여도 된다.
}

class Circle: Figure {
   class var name: String { //오버라이딩은 불가 static / class -> 오버라이딩 가능
        get {
            return "Circle"
        }
        set {

        }
    }
}

//------------------------------------------------------------

protocol Resettable {
    static func reset()
}

class Size1: Resettable {
    var width = 0.0
    var height = 0.0

    func reset() { //값 형식의 인스턴스struct 메소드에서 속성값을 바꾸려면 mutatitng 붙여줘야 한다
        width = 0.0
        height = 0.0
    }

    class func reset() { //오버 라이딩

    }
}

//------------------------------------------------------------

protocol Figure1 {
    var name: String { get }
    init(n : String)
}

struct Rectangle1: Figure1 {
    var name: String

    //생성자 직접구현, 위의 name과 아래의 n 과같이 이름이 다를 경우(Argument Lable)
    init(n: String) {
        name = n
    }
}

class Circle1: Figure1 {
    var name: String

    required init(n: String) { //상속 고려 , 모든 프로토콜 요구조건 고려 해야함 required
        name = n
    }
}

final class Triangle1: Figure1 {
    var name: String

    init(n: String) { // final 클래스는 더이상 상속 되지 않기때문에 requried 없이 요구사항 충족
        name = n
    }
}

class Oval: Circle1 { //이미 프토토콜 상속 사항 충족 , 중복선언 X
    var prop: Int

    init() {
        prop = 0
        super.init(n: "Oval")
    }

    required convenience init(n: String) {
        self.init()
    }
}

protocol Graysclae {
    init?(white: Double)
}

struct Color: Graysclae {
    init(white: Double){

    }
}

//------------------------------------------------------------

protocol List {
    subscript(idx: Int) -> Int { get }
}

struct DataStore: List { //set 넣어도 읽을 수 있기 때문에 제약 없다. , get은 필수 set은 옵션
    subscript(idx: Int) -> Int {
        get {
            return 0
        }
        set {

        }
    }
}


출처 : 어서와! Swift는 처음이지?(Programmers)
728x90

댓글

Designed by JB FACTORY