Common Swift Attributes - Relearning Note

Terry Huang
安郡尼爾筆記
Published in
5 min readApr 10, 2021

常見的 Swift Attributes 大致上分為兩類,一類是用來標註 Declaration,另一類是用來標註 Type。Attribute 會以 @ 開頭,之後是 Attribute Name,後面則有 optional 的 Attribute arguments

Declaration Attributes

available

用來標註 declaration 的生命週期。對應到相對的 Swift 版本、系統版本…等等。包含以下的 arguments

  • unavailable: 用來標註「不支援」的 platform
  • introduced: 用來標註「開始支援」的最早版本
  • deprecated: 用來標註「不推薦使用」的最早版本
  • obsoleted: 用來標註「過時(失效)」的最早版本
  • message: 用來標註額外的說明訊息,當使用者使用了 deprecated or obsoleted 的 declarations
  • renamed: 用來標註「更名」的訊息

每個 arguments 將會以下列的平台或語言為起始,或以(*) 來代表所有平台

  • iOS
  • iOSApplicationExtension
  • macOS
  • macOSApplicationExtension
  • macCatalyst
  • macCatalystApplicationExtension
  • watchOS
  • watchOSApplicationExtension
  • tvOS
  • tvOSApplicationExtension
  • swift

discardableResult

這個標註能讓 compile 忽略那些「未處理回傳值」的函式呼叫警告。在設計多功能 Protocol 時相當好用。

dynamicCallable

能將 class, structure, enumeration, or protocol 的實例作為函式來呼叫,使用上需實作 dynamicallyCall(withArguments:) dynamicallyCall(withKeywordArguments:) 至少其中之一。

main, NSApplicationMain, UIApplicationMain

主要用來標註 top-level 的 entry point。在 Objective-C 專案中,保留了 main 函式作為啟動專案的入口。

但在 swift 隱藏了這一個設計,並藉由 Attribute 來找到程序的入口。

  • iOS: 透過 main, UIApplicationMain 對應到 UIApplicationDelegate
  • macOS: 透過 main, NSApplicationMain 對應到 NSApplicationDelegate

當然,您也可以去除這個預設 attribute,並建立自己的 main 來實作接口。可參考官方說明,或是 Firefox iOS 的設計範例

nonobjc, objc

將 method, property, subscript, or initializer 標註為 objc 或 nonobjc。

常見使用情境為,需要用到 objc 的動態特性時,會需要將其標註為 objc。比如 selectors, method swizzling.

nonobjc 的 property 將無法 override 為 objc。反之則可以。

propertyWrapper

標註有 propertyWrapper 的 class, structure, or enumeration ,需實作 weappedValue,可將本身作為一個 property 的 attribute。

Type Attributes

escaping

當 closure 作為 argument 傳遞至 functions 時,其生命週期將會在 return 之後結束,但若該函式將其擷取並於之後做使用,則需要 escape(因為 function 和 closure 為 reference type)。

autoclosure

在 closure 作為 argument 傳遞時,能夠自動針對 expression 建立一個 wrap

--

--

Terry Huang
安郡尼爾筆記

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