"Type of contextual closure assumes error 2 arguments" when using shortcut in Swift 4

The following code compiles in Swift 3

extension Array where Element: Equatable {
    var removeDuplicate: [Element] {
        return reduce([]){ $0.0.contains($0.1) ? $0.0 : $0.0 + [$0.1] }
    }
}

but causes an error

error: context type of closure '(_, _) → _' expects 2 arguments, but 1 was used in the closure case

in Swift 4. How to convert this code to compile in Swift 4?

+4
source share
1 answer

A closure passed on reducetakes 2 parameters, for example. $0and $1in abbreviated notation:

extension Array where Element: Equatable {
    var removeDuplicate: [Element] {
        return reduce([]) { $0.contains($1) ? $0 : $0 + [$1] }
    }
}

(This compiles for both Swift 3 and 4).

Swift 3 $0, $0.0 $0.1. Swift 4, SE-0110 .

, : This

let clo1: (Int, Int) -> Int = { (x, y) in x + y }
let clo2: ((Int, Int)) -> Int = { z in z.0 + z.1 }

Swift 3 4,

let clo3: (Int, Int) -> Int = { z in z.0 + z.1 }

Swift 3, Swift 4.

+8

Source: https://habr.com/ru/post/1686435/


All Articles