Swift 둘러보기(A Swift Tour) - 프로토콜과 확장(Protocols and Extensions)

00yhsp·2024년 3월 26일

프로토콜을 선언하려면 protocol을 사용해야 한다.

protocol ExampleProtocol {
	var simpleDescription: String { get }
    mutating func adjust()
}

클래스, 열거형, 그리고 구조체는 프로토콜을 채택할 수 있다.

class SimpleClass: ExampleProtocol {
	var simpleDescription: String = "A very simple class."
    var anotherProperty: Int = 69105
    func adjust() {
    	simpleDescription += " Now 100% adjsted"
    }
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription

struct SimpleStructure: ExampleProtocol {
	var simpleDescription: String = "A simple structure"
    mutating func adjust() {
    	simpleDescription += " (adjusted)"
    }
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription

구조체를 수정하는 메소드를 표시하기 위해 SimpleStructure의 선언에서 mutating 키워드를 사용했다.
클래스의 메소드는 항상 클래스를 수정할 수 있으므로 SimpleClassdml tjsdjsdpsms mutating으로 표시된 메소드가 필요하지 않다.

새로운 메소드와 계산된 프로퍼티와 같이 존재하는 타입에 기능을 추가하려면 extension을 사용한다.
extension을 사용하여 다른 곳에 선언된 타입 또는 라이브러리나 프레임워크에서 가져온 타입에 프로토콜 준수를 추가할 수 있다.

extension Int: ExampleProtocol {
	var simpleDescription: String {
    	return "The number \(self)"
    }
    mutating func adjust() {
    	self += 42
    }
}
print(7.simpleDescription)

다른 명명된 타입처럼 프로토콜 이름을 사용할 수 있다.
예를 들어, 타입이 다르지만 모두 단일 프로토콜을 준수하는 객체의 콜렉션을 생성할 수 있다.
타입이 박스형 프로토콜 타입인 값으로 동작하는 경우 프로토콜 정의 외부의 메소드를 사용할 수 없다.

let protocolValue: any ExampleProtocol = a
print(protocolValue.simpleDescription)
// Prints "A very simple class.  Now 100% adjusted."
// print(protocolValue.anotherProperty)  // Uncomment to see the error

protocolValue 변수에 SimpleClass의 런타임 타입을 가지고 있더라도 컴파일러는 주어진 ExampleProtocol의 타입으로 처리한다.
즉, 프로토콜 적합성 외에 클래스가 구현하는 메소드나 프로퍼티에 실수로 접근할 수 없다.

profile
iOS Dev

0개의 댓글