[英]Range<String.Index> Versus String.Index
I am having an issue understanding the difference between Range-String.Index- and String.Index 我在理解Range-String.Index-和String.Index之间的区别时遇到问题
For example: 例如:
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());
The idea in pseudocode 伪代码中的想法
Generated HTMLBody
Pass To Function that formats
Remove all characters before StartingString
Remove all Characters After EndingString
Send NewString to Variable
Now - when I try to find the index position I cant seem to get the right value type, this is the error I am getting 现在-当我尝试找到索引位置时,我似乎无法获得正确的值类型,这就是我得到的错误
Cannot convert value of type 'Range<String.Index>?' to expected argument type 'String.Index'
This is running in a playground 这是在操场上跑步
String indices aren't integers. 字符串索引不是整数。 They're opaque objects (of type String.Index
) which can be used to subscript into a String to obtain a character. 它们是不透明的对象(类型为String.Index
),可以用于对字符串进行下标以获得字符。
Ranges aren't limited to only Range<Int>
. 范围不仅限于Range<Int>
。 If you look at the declaration of Range
, you can see it's generic over any Bound
, so long as the Bound
is Comparable
(which String.Index
is). 如果查看Range
的声明,则可以看到它在任何Bound
上都是通用的,只要Bound
是Comparable
( String.Index
是)即可。
So a Range<String.Index>
is just that. 因此, Range<String.Index>
就是这样。 It's a range of string indices, and just like any other range, it has a lowerBound
, and an upperBound
. 它是一个字符串索引范围,和其他任何范围一样,它具有一个lowerBound
和一个upperBound
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.