gpt4 book ai didi

swift - 我应该使用哪个 Swift 字符数来删除(第一个 :)?

转载 作者:搜寻专家 更新时间:2023-11-01 06:00:44 25 4
gpt4 key购买 nike

有一个removeFirst(_:)字符串上的方法。但是,该文档似乎非常通用,并且没有提及任何关于特定于字符串的内容:

k: The number of elements to remove from the collection. k must be greater than or equal to zero and must not exceed the number of elements in the collection.

var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
bugs.removeFirst(3)
print(bugs)
// Prints "["Damselfly", "Earwig"]"

事实上,它看起来与 Array 非常相似或 Collection removeFirst(_:) 的文档。

因为至少有 6 different ways要在 Swift 中获取字符计数,很难知道我应该为 k 使用哪个计数。

如果我想创建一个方法,例如 string.removePrefix("foo"),我应该使用 6 个字符计数中的哪一个?

最佳答案

removeFirst(_:)RangeReplaceableCollection 协议(protocol)的一种方法,对于任何集合,count给出其元素的数量。因此对于 RangeReplaceableCollection 类型的任何实例 a,参数 k 传递给

a.removeFirst(k)

必须大于或等于零,并且小于或等于 a.count

这适用于ArrayString(这是Character的集合)和所有其他“范围可替换集合”类型:

// Array:
var arr = [1, 2, 3, 4]
arr.removeFirst(k) // 0 <= k <= arr.count

// String:
var str = "👨‍👩‍👧‍👧"
str.removeFirst(k) // 0 <= k <= str.count

// Unicode scalar view of a string:
var u = "👨‍👩‍👧‍👧".unicodeScalars
u.removeFirst(k) // 0 <= k <= u.count

话虽如此,我会将方法实现为

extension String {
func removingPrefix(_ prefix: String) -> String? {
guard let range = range(of: prefix, options: .anchored) else {
return nil
}
return String(self[range.upperBound...])
}
}

避免不必要的索引/偏移转换。

关于swift - 我应该使用哪个 Swift 字符数来删除(第一个 :)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51992325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com