加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift要求两个泛型具有相同的类型

发布时间:2020-12-14 05:39:30 所属栏目:百科 来源:网络整理
导读:在 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
在 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:序列要求导致错误“GeneratorType不是T类型的成员”

正如@conner所指出的那样,你永远不会那样指定它,因为只有一种类型.这个更好:
func functionName<T> (lhs: T,rhs: T) -> Bool { ... }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读