Swift 泛型类型问题:"Cannot call value of non-function type 'Int'"



这是我的问题:

struct NewStack<S> {
var stacks = [S]()
mutating func addS(_ s: S) {
stacks.append(s)
}
mutating func removeLastS() {
stacks.removeLast()
}
}
var newStacks = NewStack<String>()
newStacks.addS("Eins")
newStacks.addS("Zwei")
newStacks.addS("Drei")

for stack in newStacks.stacks {
var stackCount = 1
repeat {
stackCount + 1
} while stackCount <= newStacks.stacks.count {
print("Stack (stackCount) = (stack)")
}


}

在while语句的行中,它向我发出警告:无法调用非函数类型"Int"的值如果有人能告诉我该做什么,那将非常有帮助,谢谢

您的代码有几个语法问题。首先,stackCount + 1不递增stackCount,要做到这一点,您需要stackCount += 1。其次,不能在while条件下执行代码,需要将print移动到repeat中。

for stack in newStacks.stacks {
var stackCount = 1
repeat {
stackCount += 1
print("Stack (stackCount) = (stack)")
} while stackCount <= newStacks.stacks.count
}

实际上没有必要有内部循环,您可以使用像这样的简单for循环

for stack in newStacks.stacks {
print("Stack (stack)")
}

或者,如果你想打印索引(我添加了+1,所以打印的索引从1开始(

for (index, stack) in newStacks.stacks.enumerated() {
print("Stack (index + 1) = (stack)")
}

相关内容

最新更新