根据Swift 文档:
可选绑定可以与if和while 语句一起使用,以检查可选中的值,并将该值提取到常量或变量中,作为单个操作的一部分。
该文档仅显示了使用 if 语句的可选绑定示例,例如:
if let constantName = someOptional {
statements
}
Run Code Online (Sandbox Code Playgroud)
我正在寻找使用 while 循环的可选绑定示例?
一样的
while let someValue = someOptional
{
doSomethingThatmightAffectSomeOptional(with: someValue)
}
Run Code Online (Sandbox Code Playgroud)
这是迭代链表的具体示例。
class ListNode
{
var value: String
var next: ListNode?
init(_ value: String, _ tail: ListNode?)
{
self.value = value
self.next = tail
}
}
let list = ListNode("foo", ListNode("bar", nil))
var currentNode: ListNode? = list
while let thisNode = currentNode
{
print(thisNode.value)
currentNode = thisNode.next
}
// prints foo and then bar and then stops
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1513 次 |
| 最近记录: |