Swift: loop over array elements and access previous and next elements

前端 未结 7 2576
庸人自扰
庸人自扰 2021-02-20 14:19

In Swift, I want to loop over an array and compare each element to the previous and/or next. For each comparison I will either produce a new element or nothing. Is there \"funct

7条回答
  •  情书的邮戳
    2021-02-20 15:11

    Would a simple for-loop over the range be sufficiently readable and maintainable? You could just cache the intermediate values as you iterate, so that you only access one element of the array in each iteration. If you wanted to generalize this for any comparable type, you could implement it as an extension of Array:

    extension Array where Element: Comparable {
    
        func localMinimums() -> [Int] {
            var minimums = [Int]()
    
            var currentValue = self[0]
            var nextValue = self[1]
            for index in 1..<(self.count - 1) {
                let previousValue = currentValue
                currentValue = nextValue
                nextValue = self[index + 1]
                if currentValue < nextValue && currentValue < previousValue {
                    minimums.append(index)
                }
            }
    
            return minimums
        }
    }
    
    let a = [ 1,2,2,3,5,4,2,5,7,9,5,3,8,10 ]
    let r = a.localMinimums()
    print(r)
    // [6, 11]
    

提交回复
热议问题