swift 协议示例在Swift中展示泛型

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 协议示例在Swift中展示泛型相关的知识,希望对你有一定的参考价值。

import Foundation

// Associated types allow for use of 'generic' placeholders in protocol definitions
// These associated types are defined later when the protocol is implemented
protocol Item { }
struct RandomItem: Item { }

protocol ItemStorage {
    associatedtype ItemType
    
    mutating func addItem(number: ItemType)
}

/* To Show ability to discern between protocols */
protocol RemovableStorage: ItemStorage { }

struct Cart: RemovableStorage {
    var items = [Item]()
    
    init(initialItem: Item? = nil) {
        if let initialItem = initialItem {
            items.append(initialItem)
        }
    }
    
    mutating func addItem(item: Item) {
        items.append(item)
    }
}

var newCart = Cart(initialItem: RandomItem())
newCart.addItem(RandomItem())
assert(newCart.items.count == 2)


// Associated Types with generics

struct GenericStorage<T>: ItemStorage {
    var items: [T]
    
    init(initialItem: T? = nil) {
        if let initialItem = initialItem {
            items = [initialItem]
        } else {
            items = [T]()
        }
    }
    
    mutating func addItem(item: T) {
        items.append(item)
    }
}

var basket = GenericStorage<Item>(initialItem: RandomItem())
assert(basket.items.count == 1)

/* Extension can be confined to specific types */
extension ItemStorage where Self: RemovableStorage {
    func printMessage() {
        print("I'm a Cart with removable storage")
    }
}

newCart.printMessage()

/* Extensions can also check that sub elements conform to other protocols */
extension CollectionType where Generator.Element: Comparable { }

以上是关于swift 协议示例在Swift中展示泛型的主要内容,如果未能解决你的问题,请参考以下文章

Type 应该采用啥协议来让泛型函数将任何数字类型作为 Swift 中的参数?

为什么协议的关联类型在Swift中不使用泛型类型语法?

符合 Swift 协议的泛型类型

Swift 泛型和协议扩展

Swift:检查泛型类型是不是符合协议

Swift:不能将协议与泛型混合