我正在使用let components = UItextView.text.components(separatedBy: “\n”)
函数来分隔段落。
Range<String.Index>(3..<8)
这将返回一个字符串数组。我需要能够获得范围的信息,并且还需要每个人都有一个“ id”才能识别它。我不知道该怎么做。我需要以某种方式使用令牌吗?
编辑:“ id”的含义仅是一个标识符,我必须能够识别出哪个段落与哪个组件相关。这是因为,如果在2个已经存在的段落之间添加一个段落,则通过数组进行计数将不准确。
对于范围,我想要一个单独段落的Swift Range。示例:glMemoryBarrier
答案 0 :(得分:3)
比PGDev建议的功能更多的方法:
let str = """
Paragraph 1
Paragraph 2
Paragraph 3
Paragraph 4
"""
struct ParagraphModel: Hashable {
let text: String
let range: Range<String.Index>
init(withText text: String, range: Range<String.Index>) {
self.text = text
self.range = range
}
func hash(into hasher: inout Hasher) {
hasher.combine(text)
hasher.combine(range.lowerBound)
hasher.combine(range.upperBound)
}
}
let components = str.components(separatedBy: "\n")
let models = components.compactMap { component -> ParagraphModel? in
if let range = str.range(of: component) {
return ParagraphModel(withText: component, range: range)
}
return nil
}
id
将是模型的hashValue
。
答案 1 :(得分:0)
假设我们的文本如下:
let text = """
This returns an array of strings. I am needing to be able to have the info for the ranges and also an ‘id’ for each one to be able to identify it. I have no idea how I would go about doing this. Do I need to make use of tokens somehow?
EDIT: What I mean by 'id' is just an identifier I can have to be able to recognise what paragraph relates to which component. This is because counting through the array would not be accurate if a paragraph is added between 2 already existing paragraphs.
"""
从components
中以text
分隔的"\n"
,
let arr = text.components(separatedBy: "\n")
现在,element
-arr
String, Identifier, Range
需要三件事
var requiredArray = [(String, Range<String.Index>, Int)]()
for (index, str) in arr.enumerated() {
if let range = text.range(of: str) {
requiredArray.append(str, range, index)
}
}
print(requiredArray)
在上面的代码中,
index
中str
中的arr
用作其identifier
。 range
中str
的{{1}} 因此,text
包含requiredArray
中的所有paragraphs
以及它们的text
和identifier
。
如果您仍然遇到任何问题,请告知我。