简体   繁体   English

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

[英]New Swift array syntax and Generic function

Since Xcode beta 3, we can write [int] as short hand for Array<Int> . 从Xcode beta 3开始,我们可以将[int]写成Array<Int>简写。

So we should write this: 所以我们应该这样写:

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])

For a reason I don't understand, Xcode doesn't accept the short syntax to initialize result array but accept its long equivalent Array<T.GeneratorType.Element>() . 由于我不理解的原因,Xcode不接受Array<T.GeneratorType.Element>()来初始化result数组但接受其长等效的Array<T.GeneratorType.Element>()

Am I missing something? 我错过了什么吗?

Maybe the compiler is getting confused. 也许编译器感到困惑。 This works though 这虽然有效

var result: [T.GeneratorType.Element] = []

and is more readable IMO. 并且更具可读性IMO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM