swift - 在 repeat while 循环中使用 while case 语句

标签 swift

我想弄清楚如何在 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 语句 更有能力。

Grammar of a while statement Grammar of a repeat-while statement

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/

相关文章:

ios - 检查照片库是否为空

swift - radiusCorner 和按钮

ios - 从 ios 到 watchOS 的数据传输速率(发送或接收数据所需的时间)

ios - 如何在选择时为 UICollectionViewCell 内容的扩展设置动画?

swift - 在 Swift 中将 CGColor 转换为相应的 UIColor

ios - Swift addSubview() 在使用 init 创建的 View 上(重复 :count) doesn't work

ios - 为什么 `HttpClient` 返回 `NSURLSessionDataTask` 但调用的 `API method` 除外 ` { JSONResult, error in`

ios - 无法以编程方式设置 UINavigationControllerDelegate(但可以通过 Storyboard设置)

ios - 传递数据取决于tableView单元格中的按钮

node.js - 如何在 Swift 中发布一个数组? (获取字节到我的服务器)