gpt4 book ai didi

swift - 使用泛型创建一个函数,该函数返回 Swift 中的另一个函数

转载 作者:可可西里 更新时间:2023-11-01 01:06:54 24 4
gpt4 key购买 nike

我的问题是基于 Swift 书中的 Guided Tour 章节,其中给出了以下代码:

func anyCommonElements <T, U where T: Sequence, U: Sequence,
T.GeneratorType.Element: Equatable,
T.GeneratorType.Element == U.GeneratorType.Element>
(lhs: T, rhs: U) -> Bool
{
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
anyCommonElements([1, 2, 3], [3])

这本书要求尝试修改函数以返回一个公共(public)元素数组,我能够做到。

但我开始尝试修改函数以返回另一个构建数组的函数,这就是我遇到的问题。

这是我的:

func myCommonElements<T, U where T: Sequence, U: Sequence,
T.GeneratorType.Element: Equatable,
T.GeneratorType.Element == U.GeneratorType.Element>
(lhs: T) -> (U -> Array<U.GeneratorType.Element>)
{
func makeCommon (rhs: U) -> Array<U.GeneratorType.Element>
{
var commonArray = Array<U.GeneratorType.Element>()
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
commonArray.append(lhsItem)
}
}
}
return commonArray
}
return makeCommon
}

let gatherCommon = myCommonElements([3, 4, 5, 6])
let result = gatherCommon([1, 2, 3, 4])
println(result)

我得到的错误是:

cannot convert the expression's type 
'(rhs: $T2 -> Array<$T4>)' to type 'Generator'

我理解错误,但我不确定为什么会收到此错误。我做错了什么?

最佳答案

当您调用 myCommonElements 时,您将类型 T 作为参数传递。编译器如何推断 U 的类型?声明返回类型,你会没事的。

let gc: Array<Int> -> Array<Int> = myCommonElements([3,4,5,6])

关于swift - 使用泛型创建一个函数,该函数返回 Swift 中的另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24074259/

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