如何使这个Stack结构定义?

时间:2015-10-22 17:39:58

标签: swift struct stack

我想正确地制作这个Stack结构。

如何定义' topItem'?

上面显示" 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
}

我是Swift的初学者。 这是我的第一个代码

1 个答案:

答案 0 :(得分:0)

首先,import re def contains_sublist(lst, sublst): n = len(sublst) for i in xrange(len(lst)-n+1): if (sublst == lst[i:i+n]): a = max(i, i-2) b = min(i+n+2, len(lst)) return ' '.join(lst[a:b]) sentence = 'i cant sleep what should i do' phrase = 'cant sleep' sentence_words = re.findall(r'\w+', sentence) phrase_words = re.findall(r'\w+', phrase) print contains_sublist(sentence_words, phrase_words) 应为小写。其次,不清楚你想要items返回什么。如果你想要最新的对象,你可以像这样实现它:

topItem

如果您想要第一个对象,请将其更改为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