func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
let temporaryA = a
a = b
b = temporaryA
}
var x = 5
var y = 10
swapTwoValues(&x, &y)
print("x: \(x), y: \(y)") // 输出:x: 10, y: 5
var a = "Hello"
var b = "World"
swapTwoValues(&a, &b)
print("a: \(a), b: \(b)") // 输出:a: World, b: Hello
func findIndex<T: Equatable>(of valueToFind: T, in array: [T]) -> Int? {
for (index, value) in array.enumerated() {
if value == valueToFind {
return index
}
}
return nil
}
let array = [1, 2, 3, 4, 5]
if let index = findIndex(of: 3, in: array) {
print("Index of 3: \(index)") // 输出:Index of 3: 2
}
在这个例子中,T: Equatable 是一个类型约束,它确保 T 类型必须遵循 Equatable 协议,也就是说该类型的实例可以进行相等比较。
关联类型
关联类型通常用于协议中,允许协议定义一个或多个占位符类型。这些占位符类型在协议实现时被具体化。
示例:使用关联类型定义协议
protocol Container {
associatedtype Item
mutating func append(_ item: Item)
var count: Int { get }
subscript(i: Int) -> Item { get }
}
struct Stack<Element>: Container {
var items: [Element] = []
mutating func push(_ item: Element) {
items.append(item)
}
mutating func pop() -> Element? {
return items.popLast()
}
// Container 协议要求的实现
mutating func append(_ item: Element) {
self.push(item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> Element {
return items[i]
}
}