protocol MyProtocol {
//关联类型
associatedtype ItemType
mutating func append(_ item:ItemType)
mutating func getObj(_ index:Int) -> ItemType
//下标
subscript(i:Int) -> ItemType{ get }
var count: Int { get }
}
struct MyDataSturce<T>:MyProtocol {
var count: Int {
return items.count
}
subscript(i: Int) -> (T) {
return items[i];
}
var items = [T]();
mutating func getObj(_ index: Int) -> T {
return items[index];
}
mutating func append(_ item: T) {
items.append(item)
}
}
struct MyDataSturce1<T>:MyProtocol {
var items = [T]()
subscript(i: Int) -> T {
return items[i]
}
mutating func getObj(_ index: Int) -> T {
return items[index]
}
mutating func append(_ item: T) {
items.append(item)
}
var count: Int {
return items.count
}
}
//结构体stack使用泛型T作为占位符
struct Stack<T> {
var items = [T]()
mutating func push(_ item:T){
items.append(item)
}
func pop() -> T {
return items.last!
}
//查找目标在数组中的index 泛型S满足Equatable协议
static func findIndex<S:Equatable>(ofString valueToFind:S,in array:[S]) -> Int?{
for (index,value) in array.enumerated() {
if value == valueToFind {
return index;
}
}
return nil;
}
//匹配两个数组是否相等 两个数组满足MyProtocol协议 并且两个ItemType相等 并且ItemType满足Equatable协议
static func allMatch<C1:MyProtocol,C2:MyProtocol>(_ array1:C1,_ array2:C2) -> Bool where C1.ItemType == C2.ItemType,C1.ItemType:Equatable{
if array1.count != array2.count {
return false
}
for i in 0..<array1.count {
if array1[i] != array2[i] {
return false
}
}
return true
}
}
extension Stack{
func topItem() -> T? {
return items.isEmpty ? nil : items[items.count - 1];
}
}
//扩展Stack 使用泛型满足Equatable这个协议
extension Stack where T:Equatable{
func isTop(_ item:T) -> Bool {
guard let topItem = items.last else {
return false
}
return item == topItem
}
}
//扩展MyProtocol协议 使ItemType满足Equatable协议
extension MyProtocol where ItemType:Equatable{
func startWith(_ item:ItemType) -> Bool {
return count >= 1 && self[0] == item;
}
}
//扩展MyProtocol协议 使ItemType满足为Int类型
extension MyProtocol where ItemType == Int{
var sum: Int {
var ss = 0
for i in 0..<count {
ss = self[i] + ss
}
return ss
}
}
Swift泛型的一些理解
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 目录君在此~ 《别告诉我你竟然知道——乌孙!》 目录君 第四章 乌孙国的灭顶之灾 上一章讲到,乌孙部族死的死、降的...