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

数组 – 新的Swift数组语法和通用函数

发布时间:2020-12-14 02:23:28 所属栏目:百科 来源:网络整理
导读:从 Xcode beta 3开始,我们可以将[int]写成Array Int的简写. 所以我们应该这样写: func commonElements T,U where T: Sequence,U: Sequence,T.GeneratorType.Element: Equatable,T.GeneratorType.Element == U.GeneratorType.Element (lhs: T,rhs: U) - [T.G
从 Xcode beta 3开始,我们可以将[int]写成Array< Int>的简写.

所以我们应该这样写:

func commonElements <T,U where T: Sequence,U: Sequence,T.GeneratorType.Element: Equatable,T.GeneratorType.Element == U.GeneratorType.Element>
    (lhs: T,rhs: U) -> [T.GeneratorType.Element] {
        var result = [T.GeneratorType.Element]()
        for lhsItem in lhs {
            for rhsItem in rhs {
                if lhsItem == rhsItem {
                    result += rhsItem
                }
            }
        }
        return result
}
commonElements([1,2,3,4],[2,4,6])

由于我不理解的原因,Xcode不接受短语法来初始化结果数组但接受其长等效数组< T.GeneratorType.Element>().

我错过了什么吗?

也许编译器感到困惑.这虽然有效
var result: [T.GeneratorType.Element] = []

并且更具可读性IMO.

(编辑:李大同)

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

    推荐文章
      热点阅读