[英]How can I make this Stack struct define?
I want to make this Stack struct properly. 我想正确地制作此Stack结构。
How can I define ' topItem
'? 如何定义“
topItem
”?
Is it right to show above " newstack
"? 显示在“
newstack
”上方是否正确?
struct Stack {
var Items:[String] = []
mutating func push (item:String){
Items += [item]
}
mutating func pop() -> String {
return Items.removeLast()
}
var topItem =`enter code here`
}
var newStack = Stack()
newStack.push("HistoryListController")
newStack.push("HistoryDetailViewController")
newStack.push("HistoryTimelineViewController")
newStack.push("HistoryChartViewController")
newStack.Items
if let topVC = newStack.topItem {
print("Top View Controller is \(topVC)")
//HistoryChartViewController
}
newStack.pop()
if let topVC = newStack.topItem {
print("Top View Controller is \(topVC)")
//HistoryTimelineViewController
}
I'm very beginner in Swift. 我是Swift的初学者。 This is my first code
这是我的第一个代码
First, items
should be lowercase. 首先,
items
应小写。 Second, it's not clear what you want topItem
to return. 其次,不清楚您要
topItem
返回什么。 If you want the most recent object, you could implement it like this: 如果您想要最新的对象,则可以这样实现:
struct Stack {
var items = [String]()
mutating func push (item:String){
items += [item]
}
mutating func pop() -> String {
let result = items[0]
items.removeLast()
return result
}
var topItem : String? {
return items.last
}
}
var newStack = Stack()
newStack.push("HistoryListController")
newStack.push("HistoryDetailViewController")
newStack.push("HistoryTimelineViewController")
newStack.push("HistoryChartViewController")
newStack.topItem // "HistoryChartViewController"
newStack.items
If you want the first object, change it to return items.first
. 如果需要第一个对象,请将其更改为
return items.first
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.