本文介绍了Swift数组实例方法drop(at:Int)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Swift中的Array
具有用于排除元素的几种实例方法,例如 dropFirst()
, dropLast()
, drop(while:)
等.drop(at:)
怎么办?
注意:我会使用 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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!