1.Swift的泛型用角刮號來表示(有點像C#)
- 冒號前面是泛型名稱
- 冒號後面是泛型的條件約束
- 下面這張圖的TParser為巢狀泛型(泛型中的泛型...)
2.當我要產生泛型 TResult的instance的時候
- 忽然出現Compiler build error: is not a subtype of "BaseModel"
3.這時候..Google到一個解決方案..
- 使用Protocol定義一個匿名型別
- 讓要傳入的class來實作(BaseParser<TResult>)
4. BaseModel (TResult的基底類別)
5.NestedGenericProtocol 巢狀泛型使用的Protocol,
- 需定義一個匿名型別
- 及init() 建構子 (初始化用)
7.這時候就暫時Build 成功..
8.不過要用的時候...竟然找不到Method可用,後來想想也對..,因為他目前Compiler time的型別,還是NestedGenericTypeProtocol
9.這時候想到一個方法
- 再定義一個Parser用的Protocol
- 將原本BaseParser需override的方法也定義在ParserProtocol
- 定義一個TResult匿名型別
10.這時候很感動...,終於找的到parseJson
- 除了原本的":"(冒號)來約束TParser巢狀泛型之外,再搭配where約束包含Method的ParserProtocol
11.不過悲劇來了...
- Compiler error: Cannot convert return expression of type "TParser.TResult" to return type "TResult"
12.不過這時候只要強制轉型成泛型(TResult)即可,但又出現另一個詭異的錯誤....."Command failed due to signal: Segmentation fault: 11"
13.想了半天..終於解決這個Error O.o
- 先嘗試轉型成AnyObject
- 再轉型成泛型(TResult)
14.終於成功接到資料
專案目錄結構(新增Apple子類別用來測試)
AppleManager(傳入AppleModel及AppleParser分別對應TResult及TParser)
AppleModel(裡面有個data用來存AppleParser.process()測試用資料
AppleParser 實作parseJson(不過測試用..先設定資料到model.data )
完整版可Checkout Github Source Code
Github: https://github.com/Bosian/SwiftNestedGenericType
參考資料:
http://stackoverflow.com/questions/31512318/get-al...
留言列表