我想弄清楚如何在 repeat while 循环中使用 case 语句。它在普通 while 循环中工作,但在 repeat while 循环中不工作。
indirect enum Ancestor {
case son(name: String)
case father(name: String, Ancestor)
}
创建一些枚举对象并设置递归关系
let greatGrandson: Ancestor = .son(name: "Sam")
let grandson: Ancestor = .father(name: "David", greatGrandson)
let father: Ancestor = .father(name: "John", grandson)
let grandFather: Ancestor = .father(name: "Robert", father)
递归处理并打印枚举
var relation = grandFather
while case Ancestor.father = relation {
switch relation {
case .son(let name):
fatalError("this should not happen")
case .father(let name, let thisRelation):
print("father - \(name)")
relation = thisRelation
}
}
if case .son(let name) = relation {
print("son \(name)")
}
问题是doing a while并不能正常工作,因为它会在处理之前检查条件并踢出儿子。所以我想用大小写检查重复 while 循环
以下 repeat while 循环无法编译。
repeat {
switch relation {
case .son(let name):
print("son - \(name)")
case .father(let name, let thisRelation):
print("father - \(name)")
relation = thisRelation
}
} while case Ancestor.father = relation
即使在直接 while 循环 中 while case 语句有效,但在repeat while 循环 中我得到以下错误
Enum 'case' is not allowed outside of an enum
我做错了什么,为什么我不能在 repeat while 循环中使用 while case?
最佳答案
根据 The Swift Programming Language , while 语句 比 repeat-while 语句 更有能力。
repeat-while 需要一个 Bool 表达式。
一个非常丑陋的解决方法是将case 条件放入闭包 中的if 语句 并调用它:
repeat {
switch relation {
case .son(let name):
print("son - \(name)")
case .father(let name, let thisRelation):
print("father - \(name)")
relation = thisRelation
}
} while ({ if case Ancestor.father = relation { return true }; return false }())
关于swift - 在 repeat while 循环中使用 while case 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47544660/