小编Dzo*_*ula的帖子

为什么_(下划线)在for循环(嵌套for循环)中使用?

我看到了差异,但我不明白(我不知道如何在理解代码的情况下阅读代码)

var abc = ["A", "B", "C", "D"]
var number = ["1", "2", "3"]

for i in 0 ..< abc.count {
    var str = "\(abc[i])"
    
    for _ in 0..<2{
        str += " \(number[i])"
    }
    
    print(str)
} /* output:   A11
               B22
               C33
 Fatal error: Index out of range: file Swift/ContiguousArrayBuffer.swift, line 444
 */

Run Code Online (Sandbox Code Playgroud)

当代码在嵌套的 for 循环中有 'i' 而不是 '_' 时:

var abc = ["A","B","C","D"]
var number = ["1","2","3"]

for i in 0..<abc.count {
    var str = "\(abc[i])"

    for i in 0..<2{ …
Run Code Online (Sandbox Code Playgroud)

swift

3
推荐指数
1
解决办法
109
查看次数

标签 统计

swift ×1