【问题标题】:XCode 7 Beta 3 - Array extensionXCode 7 Beta 3 - 数组扩展
【发布时间】:2015-07-11 13:15:57
【问题描述】:

XCode 7 Beta 3 之前的旧版本代码:

extension Array {
    func filterByIndex<S: SequenceType where S.Generator.Element == Int>(indices: S) -> [T] {
        return Array(PermutationGenerator(elements: self, indices: indices))
    }

    func find(includedElement: T -> Bool) -> Int? {
        for (idx, element) in self.enumerate() {
            if includedElement(element) {
                return idx
            }
        }
        return nil
    }

}

XCode 7 Beta 3 之后的新版本代码:

extension Array {
    func filterByIndex<S: SequenceType where S.Generator.Element == Int>(indices: S) -> [Element] {
        return Array(PermutationGenerator(elements: self, indices: indices))
    }

    func find(includedElement: Element -> Bool) -> Int? {
        for (idx, element) in self.enumerate() {
            if includedElement(element) {
                return idx
            }
        }
        return nil
    }
}

但是现在当我写这行时,函数 filterByIndex 给了我一个错误:

let names = (namesArr as! [String]).filterByIndex(dupes)

“[String]”没有名为“filterByIndex”的成员

有什么变化?

【问题讨论】:

  • 我同意@Arkku,代码似乎工作得很好。我想如果你能举一个例子 namesArr 和 dupes 可能有助于缩小问题范围(并确保包括这些类型)。

标签: arrays swift xcode7-beta3


【解决方案1】:

新版本的代码对我来说很好用:

[ "zero", "one", "two", "three", "four" ].filterByIndex([1, 3])
// result: [ "one", "three" ]

我假设您遇到的问题在其他地方。我最初怀疑dupes 的类型(其定义未显示)不符合泛型函数的要求,但在我的测试中,错误消息在这种情况下应该是不同的。

【讨论】:

  • let dupes = indicesOfUniques(namesArr as! [String]) public func indicesOfUniques&lt;T: Hashable&gt;(source: [T]) -&gt; [Int] { var seen: Set&lt;T&gt; = [] return source.indices.filter { if seen.contains(source[$0]) { return false } else { seen.insert(source[$0]) return true } } } 我用 indicesOfUniques 中的 Element 更改了 T 并且不起作用...
  • @BogdanBogdanov 您是否尝试过我回答中的代码?如果这对您有用,那么问题是错误的,问题在于dupes 或namesArr。要查看哪个,依次用手动创建的数组替换它们中的每一个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
  • 2015-08-25
  • 1970-01-01
  • 2015-11-26
相关资源
最近更新 更多