Swift数组实例方法drop(at:Int) [英] Swift Array instance method drop(at: Int)

查看:214
本文介绍了Swift数组实例方法drop(at:Int)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift中的Array 具有用于排除元素的几种实例方法,例如 dropFirst() 注意:我会使用 remove(at:) ,但是我正在使用的数组是let常量.

Note: I'd use remove(at:), but the array I'm working with is a let constant.

推荐答案

您可以扩展RangeReplaceableCollection协议而不是Array类型,也可以在字符串上使用它:

You can extend RangeReplaceableCollection protocol instead of Array type, this way you can use it on Strings as well:

extension RangeReplaceableCollection {
    func drop(at offset: Int) -> SubSequence {
        let index = self.index(startIndex, offsetBy: offset, limitedBy: endIndex) ?? endIndex
        let next = self.index(index, offsetBy: 1, limitedBy: endIndex) ?? endIndex
        return self[..<index] + self[next...]
    }
}


var str = "Hello, playground"
str.drop(at: 5)  // "Hello playground"


let numbers = [1, 2, 3, 4, 5]
print(numbers.drop(at: 2))  // "[1, 2, 4, 5]\n"


如果您还希望在方法中接受String.Index:


If you would like to accept also String.Index in your method:

extension RangeReplaceableCollection {
    func drop(at index: Index) -> SubSequence {
        let index = self.index(startIndex, offsetBy: distance(from: startIndex, to: index), limitedBy: endIndex) ?? endIndex
        let next = self.index(index, offsetBy: 1, limitedBy: endIndex) ?? endIndex
        return self[..<index] + self[next...]
    }
}


var str = "Hello, playground"
str.drop(at: 0)               // "ello, playground"
str.drop(at: str.startIndex)  // "ello, playground"

这篇关于Swift数组实例方法drop(at:Int)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆