gpt4 book ai didi

swift - 从正常集合索引和反向集合索引创建范围

转载 作者:行者123 更新时间:2023-11-28 06:31:32 25 4
gpt4 key购买 nike

(一个更大问题的简化示例。是的,我知道可以用更简单的方法解决这个特定的简化示例。)

我有一个包含一些 ASCII 代码点的集合,我想删除其中的前导和尾随空格。

func foo<T: BidirectionalCollection>(_ buffer: T) -> String
where T.Iterator.Element == UInt8,
T.SubSequence.Iterator.Element == T.Iterator.Element
{
if let valueStart = buffer.index(where: { $0 != 0x20 /* SP */ }),
let valueEnd = buffer.reversed().index(where: { $0 != 0x20 /* SP */ })
{
return String(bytes: buffer[valueStart ... valueEnd], encoding: .utf8)!
} else {
return ""
}
}

但是,我得到这个错误:

error: binary operator '...' cannot be applied to operands of type 'T.Index' and 'ReversedIndex'

BidirectionalCollection 的文档状态:

If you need a reversed collection of the same type, you may be able to use the collection's sequence-based or collection-based initializer.

但是,当我尝试将 buffer.reversed() 嵌入到 T() 中时,出现此错误:

error: 'T' cannot be constructed because it has no accessible initializers

因为,显然,初始化器是在其他地方定义的。

最后,我不需要整个反向集合都是某种类型。我只想能够从原始集合的索引和相应的反向集合的索引构建范围。

我在这里忽略了什么?

最佳答案

为了从 ReversedIndex 中获取基础集合的索引, 你可以简单地使用它的 base 属性(property)。

虽然注意因为方式 ReversedCollection is implemented , 这实际上将返回 高于 基础集合中给定索引的索引(因为 startIndex 映射到 endIndex – 这是一个“结束”索引)。

因此您可以简单地使用半开范围运算符 ..<为了使该索引成为非包容性上限:

func foo<T: BidirectionalCollection>(_ buffer: T) -> String
where T.Iterator.Element == UInt8,
T.SubSequence.Iterator.Element == T.Iterator.Element
{
if let valueStart = buffer.index(where: {$0 != 0x20}),
let valueEnd = buffer.reversed().index(where: {$0 != 0x20})?.base
{
// goes without saying that this will crash if String(bytes:encoding:) returns nil.
return String(bytes: buffer[valueStart ..< valueEnd], encoding: .utf8)!
} else {
return ""
}
}

或者,如果您需要使用索引本身,您可以使用 Optional map(_:) 方法结合集合的 index(before:)之前获取索引的方法:

let index = (buffer.reversed().index{ $0 != 0x20 }?.base).map{ buffer.index(before: $0) }

关于swift - 从正常集合索引和反向集合索引创建范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40191700/

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