Return swift 中函数的值

Return value from Function in swift

我有一个函数,它是某些 WebScraping 代码的一部分。在函数中相当“深”我有一个值,我想在图表中显示。为此,我需要从函数 parseElevation() 中获取变量“elevation”。我试过了

func parseElevation() -> String {

但这不起作用,因为变量“海拔”是“更深一层。

这是代码:

func parseElevation()  {
        webView.evaluateJavaScript("document.body.innerHTML") { result, error in
            guard let html = result as? String, error == nil else {
                return
            }
            
            let leftSideOfTheValue = """
            <pre style="word-wrap: break-word; white-space: pre-wrap;">
            """
            
            let rightSideOfTheValue = """
            </pre>
            """
            
            guard let leftRange = html.range(of: leftSideOfTheValue) else {
                print("cant find left range")
                return
            }
            
            guard let righRange = html.range(of: rightSideOfTheValue) else {
                print("cant find right range")
                return
            }
            
            let rangeOfTheValue = leftRange.upperBound..<righRange.lowerBound
            
            let elevationInfo = (html[rangeOfTheValue])
            
            let last9 = elevationInfo.suffix(11)
            
            if let index = (last9.range(of: ",")?.upperBound)
            {
              //prints "value"
              let afterEqualsTo = String(last9.suffix(from: index))
                print(afterEqualsTo)
                let elevation = afterEqualsTo
                
            }
        }
        
    }

有人知道如何解决这个问题吗?我一直在 swift.

中返回值时遇到问题

你不能 return 闭包中没有 return 值的东西。

您需要一个异步完成处理程序

func parseElevation(completion: @escaping (String) -> Void)  {
    webView.evaluateJavaScript("document.body.innerHTML") { result, error in
        guard let html = result as? String, error == nil else {
            return
        }
        
        let leftSideOfTheValue = """
        <pre style="word-wrap: break-word; white-space: pre-wrap;">
        """
        
        let rightSideOfTheValue = """
        </pre>
        """
        
        guard let leftRange = html.range(of: leftSideOfTheValue) else {
            print("cant find left range")
            return
        }
        
        guard let righRange = html.range(of: rightSideOfTheValue) else {
            print("cant find right range")
            return
        }
        
        let rangeOfTheValue = leftRange.upperBound..<righRange.lowerBound
        
        let elevationInfo = (html[rangeOfTheValue])
        
        let last9 = elevationInfo.suffix(11)
        
        if let index = (last9.range(of: ",")?.upperBound)
        {
            //prints "value"
            let afterEqualsTo = String(last9.suffix(from: index))
            completion(afterEqualsTo)                
        }
    } 
}

并称之为

parseElevation { elevation in
    print(elevation)
}

备注:

  • elevation 仅在闭包 {}.

    内可用
  • 请考虑仅在评估结果时才调用完成处理程序。所有 return 语句静默离开闭包。