Swift Collection扩展:选择其他所有项目

时间:2018-10-02 19:47:31

标签: swift dictionary collections

我为Swift中的Collection编写了以下扩展,该扩展从起始索引返回所有其他元素的新Collection。

1) Does the client's concurrency affect the web service's thread safety? I thought it won't and shouldn't. 
2) What are the possible reasons for generating those error messages?

可能有一些方法可以改进代码,但是我的问题是Collection是字典时。该扩展有效,但返回一个元组数组[(key:key,value:value)] 我希望扩展程序返回字典。

我已经尝试过Dictionary(uniqueKeysWithValuesMethod),一旦将它应用于everyOtherElement方法的返回值,它就可以很好地工作,但是我似乎找不到直接使之成为现实的方法。

extension Collection {
    func everyOtherElement(from theIndex: Int = 0) -> [Element]  {
        if theIndex >= self.count { return self as! [Element] }

        let start = self.index(startIndex, offsetBy: theIndex)
        let end = self.endIndex
        var everyOther = [Element]()
        var iter = start

        while iter != end {
            everyOther.append(self[iter])
            let next = index(after: iter)
            if next == end { break }
            iter = index(after: next)
        }       
                 return everyOther
        }
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

正如其他人提到的那样,字典是无序集合。如果您想返回一个Dictionary,则可以简单地扩展dictionary并过滤其他所有元素。注意,不能保证字典会保持键值对输入的顺序。话虽如此,您可以按照以下步骤完成所需的工作:

extension Dictionary {
    var everyOtherElements: Dictionary {
        var bool = true
        return filter { _ in
            defer { bool = !bool }
            return bool
        }
    }
}

let dict =  ["EN" : "Cheers", "SV" : "Skåll", "ES" : "Salud" ]
// returns [(key: "EN",
let everyOtherElements = dict.everyOtherElements  // ["ES": "Salud", "SV": "Skåll"]

关于您的评论

  

我从您的回复中了解到,我无法通过   相同的代码,我需要按类型细分吗?

您不需要扩展每种元素类型,例如,可以扩展RangeReplaceableCollection协议并返回Self,这也将使String陷入困境:

extension RangeReplaceableCollection  {
    mutating func removeEvenIndexElements() {
        var bool = true
        removeAll { _ in
            defer { bool = !bool }
            return bool
        }
    }
    mutating func removeOddIndexElements() {
        var bool = false
        removeAll { _ in
            defer { bool = !bool }
            return bool
        }
    }
    func evenIndexElements() -> Self {
        var bool = true
        return filter { _ in
            defer { bool = !bool }
            return bool
        }
    }
    func oddIndexElements() -> Self {
        var bool = false
        return filter { _ in
            defer { bool = !bool }
            return bool
        }
    }
}

var alphabet = "abcdefghijklmnopqrstuvwxyz"
alphabet.removeEvenIndexElements()
alphabet   // "bdfhjlnprtvxz"

var arr = [1,2,3,4,5,6,7,8,9,0]
arr.removeOddIndexElements()
arr        //  [1, 3, 5, 7, 9]