FE 공부/Swift

Swift _ Protocols

꼬질꼬질두부 2022. 10. 11. 12:33
반응형

형식에서 공통적으로 제공하는 멤버 목록

형식에서 구현해야하는 멤버가 선언되어있음(실제구현은 프로토콜에 포함 X)

구현은 구조체나 Class가 함 -> 프로토콜을 따른다, 프로토콜을 채용한다.

프로토콜에 선언된 멤버를 요구사항이라고 부르기도 함

 

protocol ProtocolName{
	propertyRequirments
    methodRequirments
    initializerRequirements
    subscriptRequirements
}

//상속 지원, 다중 상속도 허용
protocol ProtocolName: Protocol, ... {
}

//예제
protocol Something{
	func doSomething(){
    	
    }
}

//프로토콜 채용 문법
struct TypeName: ProtocolName, ... {
}

class TypeName: SuperClass, ProtocolName, ...{
}//클래스가 다른 클래스를 상속하고 있고 동시에 프로토콜을 채용하고 있다면 SuperClassName을 먼저 나열

struct Size: Something{
}

 

Protocol Requirements _ 프로토콜에서 속성을 선언하고 형식에서 요구사항을 구현

protocol ProtocolName{
	var name: Type {get set}
	static var name: Type {get set}
}

protocol Figure{
	var name: String {get set}
}

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

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

struct Circle: Figure {
	var name = String{
    	get{
    		return "Circle"
    	}
    	set{
    
    	}
    }
}

 

Method Requirements _ 프로토콜에서 메소드를 선언하고 요구사항 구현

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

protocol Resettable{
	func reset()
}

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

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
    }
}

 

Subscript Requirements _ 프로토콜에서 서브스크립트를 선언하고 형식에서 요구사항을 구현

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


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

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