Basic - Protocol

3386 단어 swiftiOS문법iOS

프로토콜은 해당 프로토콜을 따르는 클래스, 구조체, 열거형이 프로토콜을 만족시키는 기능을 구현을 도와주는 구문.
iOS는 스스로가 Protocol Oriented Programming (POP)라고 부르는 만큼 Protocol의 사용을 굉장히 장려하고 있다.
추후 디자인패턴, 의존성, 추상화 등의 토픽에서 자주 사용이되어진다. 꼭 알아야하는 기능이라 생각한다.

Protocol Syntax

프로토콜은 다른 클래스, 구조체, 열거형들과 유사하게 구현 및 사용할 수 있습니다.

//프로토콜 구현
protocol ViewProtocol {
	//정의
}

//프로토콜 사용
//sub-class일 경우, super-class 뒤에서 구현
class MainViewController: UIViewController, ViewProtocol {
	//프로토콜 내용들을 따름
}

Property requirements

name/type/gettable/settable 정의 필요

protocol SomeProtocol {
    var mustBeSettable: Int { get set }
    var doesNotNeedToBeSettable: Int { get }
	//타입 프로퍼티
	static var someTypeProperty: Int { get set }
}

Method requirements

name/parameter 정의 필요
default parameter 정의 불가

//구현 예시
protocol RandomNumberGenerator {
    func random() -> Double

		//타입 메소드
		static func typeMethod() 
}

//사용 예시
class LinearCongruentialGenerator: RandomNumberGenerator {
    var lastRandom = 42.0
    let m = 139968.0
    let a = 3877.0
    let c = 29573.0

    func random() -> Double {
         lastRandom = ((lastRandom a +c).truncatingRemainder(dividingBy:m))
        return lastRandom / m
    }
}

Initializer requirements

필수로 구현해야하는 이니셜라이저 지정

//구현
protocol SomeProtocol {
    init(someParameter: Int)
}

//사용 예시
class SomeClass: SomeProtocol {
    required init(someParameter: Int) {

    }
} 

Delegation

Delegation 된 class 또는 struct에 행위에 대해 권한을 넘겨주는 디자인 패턴
실제 iOS SDK에서 권장하는 MVC패턴에서 View가 Controller에게 액션을 전달하는 방법 중 하나이다.

추후 iOS Design pattern에서 더 상세하게 다루도록 한다.

Conditionally conforming to a protocol

특정 조건을 만족시킬 때만 해당 프로토콜을 따르도록 할 수 있는 기능

//Element가 TextRepresentable을 따를 경우에만 textualDescription을 사용가능
extension Array: TextRepresentable where Element: TextRepresentable {
    var textualDescription: String {
        let itemsAsText = self.map { $0.textualDescription }
        return "[" + itemsAsText.joined(separator: ", ") + "]"
    }
}

Protocol Composition

한 개의 클래스 등에서 여러 개의 프로토콜을 따를 수 있다. 상속과 다른 부분이기도 하다.

protocol Named {
    var name: String { get }
}
protocol Aged {
    var age: Int { get }
}
struct Person: Named, Aged {
    var name: String
    var age: Int
}

Checking for protocol conformance

기존의 다른 타입의 casting에서 checking 방법과 같이
is, as?, as! 를 통해서 프로토콜 체크가 가능하다.

protocol HasArea {
		var area: Double { get set }
}

class Circle: HasArea {
	var area: Double = 10.0
}

class Country {
}

let objects: [AnyObject] = [
	Circle(), Country()
]

for object in objects {
	// HasArea 이면 area nil 아니면 non-optional
	if let area = object as? HasArea {
		//area 일 경우
	} else {
		//area가 아닌 경우
	}
}

Optional protocol requirements

프로토콜에서 필수로 구현하는 것이 아닌 선택적으로 조건을 구현할 수 있는 기능이 있다.
프로토콜과 해당하는 프로퍼티 또는 함수에 @objc 키워드를 붙여 사용.

프로토콜에서 필수로 구현하는 것이 아닌 선택적으로 조건을 구현할 수 있는 기능이 있다.
프로토콜과 해당하는 프로퍼티 또는 함수에 @objc 키워드를 붙여 사용.

#학습에 대한 내용으로 틀린 내용이 있을 수 있습니다.
#댓글로 남겨주시면 더 좋은 게시글로 수정하도록 하겠습니다.

좋은 웹페이지 즐겨찾기