swift 協議泛型associatedtype

2021-10-24 02:35:00 字數 593 閱讀 8846

協議 中不支援這中方式寫泛型

需要使用associatedtype關鍵字

protocol container

subscript(i:int)->itemtype

}

可以實現協議看下具體如何使用

//: from  

import uikit

protocol container

subscript(i:int)->itemtype

}struct instack: container

subscript(i: int) -> int

typealias itemtype = int

//自定義方法

mutating func pop()->int

}

同時也可以新增約束

associatedtype itemtype:equatable
//協議可作為它自身的要求出現

protocol suffixablecontainer:container

Swift中協議與泛型的應用

1.方法的泛型 泛型約束 冒號後邊跟class或者協議,傳入的引數somet和someu必須是遵循該協議或類 naarray類,comparable協議 func somefunction somet t,someu u func compartwo a t,b t bool與oc中的id有點類似,...

Swift之泛型型別與泛型引數

import foundation func swaptwoints inout a int,inout b int func swaptwostrings inout a string,inout b string func swaptwodoubles inout a double,inout ...

swift 筆記 二十 泛型

泛型 泛型是為了解決在針對不同資料型別,而做了同一種功能的操作導致的每個型別我們都要寫乙份 的問題。有了泛型,我們可以只寫乙份邏輯 而適應於不同的資料型別。func swapint inout num1 int,inout num2 int func swapdouble inout num1 do...