gpt4 book ai didi

generics - Swift 要求两个泛型是同一类型

转载 作者:搜寻专家 更新时间:2023-10-30 22:12:17 28 4
gpt4 key购买 nike

在 Swift 编程语言中我看到了一个例子

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
}

似乎 T.GeneratorType.Element == U.GeneratorType.Element 意味着分解序列时生成的元素共享相同的基础类型。所以我可以做

anyCommonElements("123", "1234")
anyCommonElements([1, 2, 3], [1])

但不是

anyCommonElements("123", [1, 2])

但是T: Sequence, U: Sequence的意思是参数T和U必须是序列,比如String或者Array。

使用 where 子句编写接受两个参数 T 和 U 的函数的正确方法是什么?这两个参数必须是同一类型?省略 T: Sequence, U: Sequence 要求会导致错误“GeneratorType is not member of type T”

最佳答案

正如@conner 所指出的,但您永远不会那样指定它,因为只有一种类型。这样更好:

func functionName<T> (lhs: T, rhs: T) -> Bool { ... }

关于generics - Swift 要求两个泛型是同一类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24069473/

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