Swift Protocol Q&A - Relearning Note

Terry Huang
安郡尼爾筆記
Published in
2 min readNov 24, 2020

Q: 什麼是 Protocol

Protocol 用來定義一個特定「任務」「功能」的藍圖,包含其「方法」「屬性」以及「其他的要求」。Protocol 能被 Class, Struct, Enumeration 採用並實踐。

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.
– The Swift Programming Language Guide by Apple

Q: Protocol 能定義哪些需求

  • 屬性需求 Property Requirements
  • 方法需求 Method Requirements
  • 初始化需求 Initializer Requirements
Protocol with “Property”, “Method” and “Initializer” requirements

Q: Swift Protocol vs Java Interface

類似功能

  • 能夠用於抽象化(Abstraction)以及委派(Delegation)等設計模式(Design Pattern)
  • 可作為型別用於變量(Protocols as Types)與集合( Collections of Protocol Types)。也能實例確認(Checking for Protocol Conformance)
“WithName” Protocol as Types in Employee

Swift Protocol 功能

  • Protocol 除了方法需求外,能定義屬性、初始化需求
  • Protocol 能以 Extension 在既有的存取範圍中,延伸新增屬性、方法,並能實作其邏輯行為
Protocol Extension with function implementation
  • Protocol 能「繼承」Protocol(如圖中 Resident)
Protocol Inheritance
  • Protocol 支援 Composition(如圖中 sayHello)
Parameter with Protocol Composition

--

--

Terry Huang
安郡尼爾筆記

Co-Founder of LiRise Co.,Ltd. In charge of innovative affairs development. Tags: Guitar, Golf, Photograph, Cocktail, Dance, Diving, Travel.