范围<String.Index>与String.Index

时间:2019-07-11 00:37:41

标签: swift swift-playground

我在理解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'

这是在操场上跑步

1 个答案:

答案 0 :(得分:0)

字符串索引不是整数。它们是不透明的对象(String.Index类型),可用于将其下标为String以获取字符。

范围不仅限于Range<Int>。如果查看Range的声明,只要BoundBoundComparable是),就可以看到它在任何String.Index上都是通用的。

所以Range<String.Index>就是这样。这是一个字符串索引范围,与其他任何范围一样,它具有一个lowerBound和一个upperBound