gpt4 book ai didi

Swift 代码错误第 21 页

转载 作者:行者123 更新时间:2023-11-30 10:06:51 25 4
gpt4 key购买 nike

大家好,我正在学习 Swift,刚刚浏览了 Apple 在应用商店上提供的书籍。第 21 页上有一些代码,但我无论如何也无法让它工作。只是想知道是否有人可以阐明。我很确定这是一个更新,但如果有人能指出我或提供帮助,那就太好了。这是从书中摘取的代码(是的,我已经准确地重新输入了)

func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]

hasAnyMatches(numbers, condition: lessThanTen)

但是,当我将代码放入其中时,它会发生变化并在函数调用中显示条件参数,如下所示。我应该指出,我在条件后放置了一个问号:因为我不确定 Int -> Bool 需要什么数据类型。

I have placed a question mark after condition as I am not entirely sure what Int -> Bool is asking for.

最佳答案

类型Int -> Bool是一个函数类型,它采用 Int 类型的单个参数,并返回 Bool 类型的值。从这个意义上说,hasAnyMatches是一个高阶函数,因为除了整数数组之外,它还需要一个函数作为参数。因此,您可以发送例如函数引用(对 (Int) -> Bool 函数)或作为 hasAnyMatches) 的第二个参数的闭包.

下面是一个示例,调用 hasAnyMatches 1. 函数引用; 2. 匿名闭包; 3.预定义的闭包:

func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]

/* 1. function reference: to 'lessThanTen' function */
hasAnyMatches(numbers, condition: lessThanTen)

/* 2. anonymous (trailing) closure: (Int) -> Bool: "integer less than 0?" */
hasAnyMatches(numbers) { myInteger in myInteger < 0 }
hasAnyMatches(numbers) { $0 < 0 } /* short form */

/* 3. pre-defined closure: (Int) -> Bool: "integer larger than 0?" */
let myIntToBoolClosure : (Int) -> Bool = {
myInteger in
return myInteger > 0
}
hasAnyMatches(numbers, condition: myIntToBoolClosure)

关于Swift 代码错误第 21 页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35457440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com