在重复while循环中使用while case语句

时间:2017-11-29 03:38:17

标签: swift

我试图找出如何在重复while循环中使用case语句。它在plain 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)")
}

问题是做一段时间不能正常工作,因为它会检查条件并在处理之前踢出儿子。所以我想用case检查重复while循环

以下重复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 case语句仍可正常工作,但在 重复循环 中得到以下错误

  

Enum' case'不允许在枚举之外

我做错了什么,为什么我不能在重复while循环中使用while case?

0 个答案:

没有答案