Boo*_*oon 42 optional for-in-loop swift2
使用可选的for-in循环的正确方法是什么?
现在我总是在循环之前执行可选绑定.还有其他成语吗?
let optionalInt:[Int]? = [1, 2, 3]
if let optionalInt = optionalInt {
for i in optionalInt {
print(i)
}
}
Run Code Online (Sandbox Code Playgroud)
Ric*_*hiy 45
如果要将一组操作应用于数组的所有元素,则可以用forEach{}闭包替换for循环并使用可选的链接:
var arr: [Int]? = [1, 2, 3]
arr?.forEach{print($0)}
Run Code Online (Sandbox Code Playgroud)
小智 20
我认为没有正确的方法.有许多不同的方式,它真正归结为你喜欢的,Swift充满了各种功能,可以让你的程序看起来非常好,根据你的选择.
以下是我能想到的一些方法:
let optionalInt:[Int]? = [1, 2, 3]
for i in optionalInt! { print(i) }
for i in optionalInt ?? [] { print(i) }
for i in optionalInt as [Int]! { print(i) }
Run Code Online (Sandbox Code Playgroud)
你可以写这个:
let optionalInt:[Int]? = [1, 2, 3]
for i in optionalInt ?? [Int]() {
print(i)
}
Run Code Online (Sandbox Code Playgroud)
但我建议你避免使用可选值,例如你可以像这样写:
var values = [Int]()
// now you may set or may not set
for i in values {
print(i)
}
Run Code Online (Sandbox Code Playgroud)
或者,如果要使用可选值,并且在函数中调用此代码可以使用guard:
guard let values = optionalInt else { return }
for i in values {
print(i)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12230 次 |
| 最近记录: |