我在理解Range-String.Index- 和 String.Index 之间的区别时遇到问题
例如:
func returnHtmlContent() -> String {
let filePath = URL(string:"xxx.htm")
filePath?.startAccessingSecurityScopedResource();
let htmlFile = Bundle.main.path(forResource: "getData", ofType: "htm");
let html = try! String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8);
filePath?.stopAccessingSecurityScopedResource();
return html;
};
func refactorHtml(content: String) -> String {
let StartingString = "<div id="1">";
let EndingString = "</div></form>";
func selectString() -> String {
var htmlContent = returnHtmlContent();
let charLocationStart = htmlContent.range(of: StartingString);
let charLocationEnd = htmlContent.range(of: EndingString);
htmlContent.remove(at: charLocationStart);
return htmlContent;
};
let formattedBody = selectString();
return formattedBody;
};
refactorHtml(content: returnHtmlContent());
伪代码中的想法
Generated HTMLBody
Pass To Function that formats
Remove all characters before StartingString
Remove all Characters After EndingString
Send NewString to Variable
现在 - 当我尝试找到索引位置时,我似乎无法获得正确的值类型,这是我遇到的错误
Cannot convert value of type 'Range<String.Index>?' to expected argument type 'String.Index'
这是在操场上跑步
字符串索引不是整数。它们是不透明的对象(类型为 String.Index
(,可用于下标到字符串中以获取字符。
范围不仅限于 Range<Int>
。如果你看一下Range
的声明,你可以看到它在任何Bound
上都是通用的,只要Bound
是Comparable
(String.Index
是
所以Range<String.Index>
就是这样。它是一个字符串索引的范围,就像任何其他范围一样,它有一个lowerBound
和一个upperBound
。