I am having an issue understanding the difference between Range-String.Index- and 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.
Ranges aren't limited to only 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).
So a Range<String.Index>
is just that. It's a range of string indices, and just like any other range, it has a lowerBound
, and an upperBound
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.