gpt4 book ai didi

ios - Swift 中的堆栈实现

转载 作者:搜寻专家 更新时间:2023-10-31 08:33:48 24 4
gpt4 key购买 nike

我是 Swift 和 iOS 编程的新手。

我正在尝试测试一个简单的算法并需要一个堆栈数组。不必花哨(Int 堆栈就可以)。

我从 The Swift Programming Language documentation 得到 Stack 实现:

struct IntStack {
var items = [Int]()
mutating func push(item: Int) {
items.append(item)
}
mutating func pop() -> Int {
return items.removeLast()
}
mutating func count() -> Int {
return items.count
}
mutating func show() {
println(items)
}
}

计数和显示功能是我的贡献。但是当我尝试声明堆栈数组时出现错误...

var lines = IntStack()[5]

“IntStack”没有名为下标的成员

我猜它与 Optionals 有关,但可以弄清楚它是什么。

有什么帮助吗?

最佳答案

详情

  • swift 5.1,Xcode 11.3.1

通用堆栈实现

Stackable protocol

protocol Stackable {
associatedtype Element
func peek() -> Element?
mutating func push(_ element: Element)
@discardableResult mutating func pop() -> Element?
}

extension Stackable {
var isEmpty: Bool { peek() == nil }
}

Stack

struct Stack<Element>: Stackable where Element: Equatable {
private var storage = [Element]()
func peek() -> Element? { storage.last }
mutating func push(_ element: Element) { storage.append(element) }
mutating func pop() -> Element? { storage.popLast() }
}

extension Stack: Equatable {
static func == (lhs: Stack<Element>, rhs: Stack<Element>) -> Bool { lhs.storage == rhs.storage }
}

extension Stack: CustomStringConvertible {
var description: String { "\(storage)" }
}

extension Stack: ExpressibleByArrayLiteral {
init(arrayLiteral elements: Self.Element...) { storage = elements }
}

用法

var stack = Stack<Int>()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.peek())
print(stack.pop())
print(stack)
print(stack == Stack<Int>())
stack = [3,2,1]
print(stack)

关于ios - Swift 中的堆栈实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31462272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com