WWDC) Protocol-Oriented Programming in Swift

Havi·2020년 12월 25일
0

WWDC

목록 보기
2/7

WWDC 영상 주소

Object-oriented programming에서 클래스를 사용할 경우 다음과 같은 장점이 있다.

  • Encapsulation
  • Access control
  • Abstraction
  • Namespace
  • Expressive syntax
  • Extensibility

하지만 Swift에서는 Struct와 enum이 Calss의 기능을 대체할 수 있다.

Class는 inheritance라는 막강한 기능을 가지고 있다. 하지만 Too many copies 때문에 code를 slow down 할 뿐 아니라, Threads가 mutable state를 sharing하는 race conditions에서 불안정하다. 따라서 Locks를 걸어줘야 하는데 이는 code를 더 slow down 시킨다. 이는 Deadlock을 발생시킬 수 있으며 복잡성과 버그를 도출할 수 있다.

Objective-C에서 Collection type을 iterating할 때 값을 바꾸는 것은 클래스 타입이기 때문에 안전하지 않다고 한다. 하지만 Swift는 괜찮다. 왜냐? Collections는 기본적으로 Struct로 이루어진 Value types이기 때문이다. 따라서 iterating과 modifying은 distinct하다.

Class는 너무 monolithic(단단히 하나로 짜여져있는)하다. 오직 하나의 superclass밖에 가지지 못한다. 따라서 extension으로 원하는 inheritance를 가지기 힘들고, stored properties가 있을경우 이를 무조건적으로 수용해야한다. 이는 initialization burden이 된다.

Class를 사용할 경우 함수에서 as! ASubclass로 다운 캐스팅 해서 사용할 일이 잦다. 이를 "Code Smell"이라 하곤 한다. 따라서 우리는 더 나은 abstraction mechanism을 필요로 한다. 이것이 바로 Protocol Oriented Programming이다.

protocol로 선언할 경우 method가 dynamic runtime check를 static check로 바꿀 수 있다. 또한 Self-Requirement를 사용함으로써 hetetogeneous함수를 homogeneous 다음과 같이 바꿀 수 있다.

정리하자면 Self Requirement를 썼을 때와 쓰지 않았을 때 다음과 같은 장점이 있다.

이 후 예제들은 정리 x

또한 protocol extensions를 통한 확장이 가능하다.

profile
iOS Developer

0개의 댓글