Arrays 如何在Swift中识别数组中特定值的连续出现?

Arrays 如何在Swift中识别数组中特定值的连续出现?,arrays,swift,evaluation,Arrays,Swift,Evaluation,我需要评估一个数组是否有两个连续出现的特定值。例如,我想评估一个数组在连续索引位置是否有两个值“1”的实例。我只希望对于值“1”的重复(即,不适用于其他重复值)和仅适用于连续索引位置的重复,该值计算为“真”。我发现了许多模糊不清的类似问题和解决方案,但没有一个与这种特定情况相匹配。具体例子如下: [0,1,1,0,2,0] // Evaluates to True Because of Two Consecutive 1's [0,1,0,1,2,2] // Evaluate

我需要评估一个数组是否有两个连续出现的特定值。例如,我想评估一个数组在连续索引位置是否有两个值“1”的实例。我只希望对于值“1”的重复(即,不适用于其他重复值)和仅适用于连续索引位置的重复,该值计算为“真”。我发现了许多模糊不清的类似问题和解决方案,但没有一个与这种特定情况相匹配。具体例子如下:

    [0,1,1,0,2,0]  // Evaluates to True Because of Two Consecutive 1's
    [0,1,0,1,2,2]  // Evaluates to False, In Spite of Repeated 2's and Multiple (Non-Consecutive) Instances of 1
使用:

let specificValue: Int = 1
let numberArray: [Int] = [0,1,1,0,2,0]
let hasConsecutiveValue = checkForConsecutiveValue(value: specificValue, within: numberArray)

您可以使用for循环来实现这一点。我在
序列
协议中做了一些扩展,使解决方案更加通用:

extension Sequence where Element: Equatable {
    func consecutiveOccurrences(of element: Element) -> Bool {
        var appeared = false
        for item in self {
            if item == element, appeared {
                return true
            } else if item == element {
                appeared = true
            } else {
                appeared = false
            }
        }
        return false
    }
}

print([0,1,1,0,2,0].consecutiveOccurrences(of: 1)) // true
print([0,1,0,1,2,2].consecutiveOccurrences(of: 1)) // false

@gcharita kkkk我们让他很难过。他至少展示了一些effort@Eric33187
用于numberraray.index.dropLast()中的索引{
谢谢你,Leo.lol.我添加了一个保护声明。现在大家都高兴了吗?哈哈哈,如果用户拥有这个特权(足够的声誉)是的。但是如果你编辑自己的PostOk更有意义,那就更好了。谢谢你的提示。也谢谢所有的指针大家!一个简单的
for
循环,比较当前值和上一个(或下一个)值怎么样?为什么这个如此特别,以至于你还没有尝试过那个简单的解决方案?
extension Sequence where Element: Equatable {
    func consecutiveOccurrences(of element: Element) -> Bool {
        var appeared = false
        for item in self {
            if item == element, appeared {
                return true
            } else if item == element {
                appeared = true
            } else {
                appeared = false
            }
        }
        return false
    }
}

print([0,1,1,0,2,0].consecutiveOccurrences(of: 1)) // true
print([0,1,0,1,2,2].consecutiveOccurrences(of: 1)) // false