funcswapTwoValues<T>(_a: inout T, _b: inout T){let temporaryA = a a = b b = temporaryA}var x =5var y =10swapTwoValues(&x, &y)print("x: \(x), y: \(y)")// 输出:x: 10, y: 5var 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
}
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]
}
}