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

前端 未结 7 2578
庸人自扰
庸人自扰 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 14:48

    I think Martin R's answer is smart, though I try answering using the other way.

    let a = [ 1,2,2,3,5,4,2,5,7,9,5,3,8,10 ]
    
    func withPrevAndNext(`default`: U, _ f: @escaping (T, T, T) -> (U)) -> (T) -> (U) {
        var previous: T?
        var current: T?
    
        return { next in
            defer { (previous, current) = (current, next) }
            guard let prev = previous, let curt = current else { return `default` }
            return f(prev, curt, next)
        }
    }
    
    let r = a.enumerated().compactMap(withPrevAndNext(default: .none) { prev, curt, next -> Int? in
        curt.1 < prev.1 && curt.1 < next.1 ? curt.0 : .none
    })
    
    print(r)
    // [6, 11]
    

提交回复
热议问题