2014-06-10 3 views
1

나는 언어 책을 프로그래밍 스위프트 통해 이동하고 나는 이것을 완전히 이해하지 않는다 : 당신이 정확히 여기 무슨 일이 일어나고 있는지의 조금 더 설명 할 수 있다면전달 FUNC

//I don't understand 'condition: Int -> Bool' as a parameter, what is that saying? 
func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool { 

    //So here i see we are iterating through an array of integers 
    for item in list { 

     //I see that condition should return a Bool, but what exactly is being compared here? Is it, 'if item is an Int return true'?? 
     if condition(item) { 
      return true 
     } 
    } 

    return false 
} 


//This func I understand 
func lessThanTen(number: Int) -> Bool { 
    return number < 10 
} 

var numbers = [20, 19, 7, 20] 

hasAnyMatches(numbers, lessThanTen) 

이 될 것이다 매우 감사. 나는 코멘트에서 대부분의 질문을하므로 읽기가 쉽지만, 혼란스러운 것은 condition: Int -> Bool을 매개 변수로 사용합니다.

+0

아마도이 설명은 진행 상황을 이해하는 데 도움이됩니다. 신속하게 모든 기능에 유형이 있습니다. 'lessThanTen()'함수의 타입은 "Int Intl, Bool"을 반환합니다.이 함수는 구문 적으로'Int -> Bool'으로 표현됩니다. 다른 유형의 함수를 제공하면 코드가 컴파일되지 않습니다. –

답변

3

를이 책에 언급 된 바와 같이, 두 번째 인수는

// 'condition: Int -> Bool' is saying that it accepts a function that takes an Int and returns a Bool 
func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool { 

    // Takes each item in array in turn 
    for item in list { 

     // Here each 'item' in the list is sent to the lessThanTen function to test whether the item is less than 10 and returns true if it is the case and executes the code, which in turn returns true 
     if condition(item) { 
      return true 
     } 
    } 

    return false 
} 


// This function is sent as the second argument and then called from hasAnyMatches 
func lessThanTen(number: Int) -> Bool { 
    return number < 10 
} 

var numbers = [20, 19, 7, 20] 

hasAnyMatches(numbers, lessThanTen) 
(나는 코드 주석 설명했습니다에 실제로 무슨 일이 일어나고 있는지)하는 기능입니다

제공된 시나리오에서 루프는 7에 도달 할 때까지 계속 실행되며,이 시점에서 true가 반환됩니다. 10 이하에 숫자가 없으면 함수는 false를 반환합니다.

+0

우수 설명, 고마워요. – random

1

condition: Int -> Bool은 함수로 더 잘 알려진 closure을 전달하는 구문입니다. 그 서명에서 볼 수 있듯이

기능 lessThanTen

inputTypes->outputType는 기본적으로 함수를 정의하는 데 필요한 모든 것입니다, Int -> Bool의 유형이있다!

그것은뿐만 아니라 다음과 같이 작동합니다 :

hasAnyMatches(numbers, { number in ; return number < 10 }) 

// Or like this, with trailing closure syntax 
hasAnyMatches(numbers) { 
    number in 
    return number < 10 
} 
+0

아시다시피, 더 가까운 구문이 의미가 있습니다. 도와 주셔서 감사합니다 – random

관련 문제