无法理解 Swift 中的 for 循环 3
Trouble understanding a for loop in Swift 3
我正在研究一些代码以尝试学习 Swift 3. 我遇到了这个 for 循环,但无法理解它到底在做什么。如果你理解它,你能试着用解释来分解它吗?
var size = 0
var candidate = (value: 0, index: 0)
for i in 0..<count {
if size == 0 {
candidate = (A[i], i)
size += 1
} else {
if candidate.value != A[i] {
size -= 1
} else {
size += 1
}
}
}
// set variable "size" to the value of zero
var size = 0
// set variable "candidate" to be a NAMED TUPLE with initial values (0,0)
var candidate = (value: 0, index: 0)
// start a FOR loop from 0 to "count" which by the way has not been defined yet, so that might be a problem.
for i in 0..<count {
// if size is zero, then we set candidate equal to ARRAY "A" of index "i" and increment 'size'... and by the way, this Array "A" has not been defined anywhere, so that might be a problem.
if size == 0 {
candidate = (A[i], i)
size += 1
// otherwise, we do one of two things: 1) if the 'candidate' tuple's (value:) parameter is NOT equal to the value of Array 'A''s index of 'i', then we decrement 'size' ... by the way this Array 'A' has not yet been defined so that might be a problem... or 2) increment the value of 'size.'
} else {
if candidate.value != A[i] {
size -= 1
} else {
size += 1
}
}
}
所以看起来应该有一个名为 'A'
的数组
和'count'实际上应该是A.count
基本上,循环是(似乎正在尝试)遍历数组 'A' 并比较相邻值并根据这些比较的结果调整 'size' 变量。
我正在研究一些代码以尝试学习 Swift 3. 我遇到了这个 for 循环,但无法理解它到底在做什么。如果你理解它,你能试着用解释来分解它吗?
var size = 0
var candidate = (value: 0, index: 0)
for i in 0..<count {
if size == 0 {
candidate = (A[i], i)
size += 1
} else {
if candidate.value != A[i] {
size -= 1
} else {
size += 1
}
}
}
// set variable "size" to the value of zero
var size = 0
// set variable "candidate" to be a NAMED TUPLE with initial values (0,0)
var candidate = (value: 0, index: 0)
// start a FOR loop from 0 to "count" which by the way has not been defined yet, so that might be a problem.
for i in 0..<count {
// if size is zero, then we set candidate equal to ARRAY "A" of index "i" and increment 'size'... and by the way, this Array "A" has not been defined anywhere, so that might be a problem.
if size == 0 {
candidate = (A[i], i)
size += 1
// otherwise, we do one of two things: 1) if the 'candidate' tuple's (value:) parameter is NOT equal to the value of Array 'A''s index of 'i', then we decrement 'size' ... by the way this Array 'A' has not yet been defined so that might be a problem... or 2) increment the value of 'size.'
} else {
if candidate.value != A[i] {
size -= 1
} else {
size += 1
}
}
}
所以看起来应该有一个名为 'A'
的数组和'count'实际上应该是A.count
基本上,循环是(似乎正在尝试)遍历数组 'A' 并比较相邻值并根据这些比较的结果调整 'size' 变量。