1. Swift
- 클래스로 구현된 타입은 별로 없고 대부분 구조체로 기본 타입이 구현
- 구조체는 상속이 되지 않음 -> 프로토콜과 익스텐션의 힘
- 익스텐션 : 기존 타입의 기능을 확장
- 프로토콜 : 프로토콜을 채택한 타입이 원하는 기능을 강제로 구현
2. 프로토콜 초기구현
- 무언가 보내고 받을 수 있는 프로토콜을 정의하고 extension을 통해 기능을 구현하기
- 익스텐션을 통한 프로토콜의 실제 구현
protocol Receiveable {
func received(data: Any, from: Sendable)
}
extension Receiveable {
func received(data: Any, from: Sendable) {
print("\(self) received \(data) from \(from)")
}
}
protocol Sendable {
var from: Sendable { get }
var to: Receiveable? { get }
func send(data: Any)
static func isSendableInstance(_ instance: Any) -> Bool
}
extension Sendable {
var from: Sendable {
return self
}
func send(data: Any) {
guard let receiver: Receiveable = self.to else {
print("Message has no receiver")
return
}
receiver.received(data: data, from: self.from)
}
static func isSendableInstance(_ instance: Any) -> Bool {
if let sendableInstance: Sendable = instance as? Sendable {
return senableInstance.to != nil
}
return false
}
}
class Message: Sendable, Receiveable {
var to: Receiveable?
}
class Mail: Sendable, Receiveable {
var to: Receiveable?
}
let myPhoneMessage: Message = Message()
let yourPhoneMesssage: Message = Message()
myPhoneMessage.send(data: "Hello")
myPhoneMessage.to = yourPhoneMesssage
myPhoneMessage.send(data: "Hello")
let myMail: Mail = Mail()
let yourMail: Mail = Mail()
myMail.send(data: "Hi")
myMail.to = yourMail
myMail.send(data: "Hi")
myMail.to = myPhoneMessage
myMail.send(data: "Bye")
Message.isSendableInstance("Hello")
Message.isSendableInstance(myPhoneMessage)
Message.isSendableInstance(yourPhoneMesssage)
Mail.isSendableInstance(myPhoneMessage)
Mail.isSendableInstance(myMail)
class Mail: Sendable, Receiveable {
var to: Receiveable?
func send(data: Any) {
print("Mail의 send 메서드는 재정의되었습니다.")
}
}
let mailInstance: Mail = Mail()
mailInstance.send(data: "Hello")
3. 기본 타입 확장
- 초기구현을 통해 기본 타입을 확장하여 내가 원하는 기능을 공통적으로 추가해 볼 수 있음
protocol SelfPrintable {
func printSelf()
}
extension SelfPrintable {
func printSelf() {
print(self)
}
}
extension Int: SelfPrintable { }
extension String: SelfPrintable { }
extension Double: SelfPrintable { }
1024.printSelf()
3.14.printSelf()
"Jimin".printSelf()