Roman Romanenko
Roman Romanenko

Reputation: 766

Swift 2.1 Closure

At first, I apologize for my English! Please help me detect when I was wrong.

let arrayInt = [0, 1, 2, 3, 4, 5, 7, 8, 9]

func myF(array: [Int], cl:(n1: Int, n2: Int) -> Bool) -> Int {

    var number : Int

    for value in array {
        if cl(n1: number, n2: value) {
            number = value
        }
    }

    return number

}

myF(arrayInt, { cl: (n1: Int, n2: Int) -> Bool in 
    return n1 < n2
})

The function takes an array of Int and closure returns Int. Closure should take two Int numbers and return Bool yes or no. It is necessary to walk in a loop through the array and compare elements of array with variable using closure . If closure returns yes, you write the value of the array into variable. At the end of the function returns the variable. We need find max and min value in array.

I have 3 issue:

  1. consecutive statements on a line must be separated by ';'
  2. expected expression
  3. contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored

Please don't proposed me use method "sort()". I am learning of "closure".

Upvotes: 0

Views: 480

Answers (2)

Kid Limonade
Kid Limonade

Reputation: 80

First replace:

myF(arrayInt, { cl: (n1: Int, n2: Int) -> Bool in

by:

myF(arrayInt, cl: { (n1: Int, n2: Int) -> Bool in

because cl is the parameter name and all included in { } is the closure. Second initialize number in myF function replacing:

var number : Int

by:

var number = array[0]

if the goal of the closure is to find max or min value.

Upvotes: 0

Andrey Gershengoren
Andrey Gershengoren

Reputation: 916

First of all you need to initialize your number variable: var number : Int -> var number = 0

Second, the function call with closure is not correct. There are several ways to call a closure:

let y = myF(arrayInt, cl: { (n1: Int, n2: Int) -> Bool in
    return n1 < n2
})

or

let x = myF(arrayInt) { (n1, n2) -> Bool in
    return n1 < n2
}

or even

let z = myF(arrayInt) { n1, n2 in
    return n1 < n2
}

and

let w = myF(arrayInt) { $0 < $1 }

This link and this one should help you

Full code sample:

let arrayInt = [1, 2, 3, 0, 4]

func myF(array: [Int], cl: (n1: Int, n2: Int) -> Bool) -> Int {
    var number = 0
    for i in array {
        if cl(n1: number, n2: i) {
            number = i
        } 
    }
    return number
}


let x = myF(arrayInt) { (n1, n2) -> Bool in
    return n1 < n2
}

Upvotes: 2

Related Questions