美文网首页
Swift 自定义下标

Swift 自定义下标

作者: gaookey | 来源:发表于2020-09-10 10:56 被阅读0次

    Swift 是允许我们自定义下标的。这不仅包含了对自己写的类型进行下标自定义,也包括了对那些已经支持下标访问的类型 (没错就是 Array 和 Dictionay) 进行扩展。

    extension Array {
        subscript(input: [Int]) -> ArraySlice<Element> {
            get {
                var result = ArraySlice<Element>()
                for i in input {
                    assert(i < self.count, "Index out of range")
                    result.append(self[i])
                }
                return result
            }
            
            set {
                for (index,i) in input.enumerated() {
                    assert(i < self.count, "Index out of range")
                    self[i] = newValue[index]
                }
            }
        }
    }
    
    
    var arr = [1,2,3,4,5]
    //[1, 3, 4]
    arr[[0,2,3]]
    arr[[0,2,3]] = [-1,-3,-4]
    //[-1, 2, -3, -4, 5]
    arr
    

    摘录来自: 王巍 (onevcat). “Swifter - Swift 必备 Tips (第四版)。”

    相关文章

      网友评论

          本文标题:Swift 自定义下标

          本文链接:https://www.haomeiwen.com/subject/uedjektx.html