字符串比较通过Alamofire获得的数据给出了意外结果

时间:2019-01-03 17:29:01

标签: swift string comparison

我在Swift中的字符串比较有问题(我可能在这里错了)。

下面是我遇到此问题的方法。

这是我的输入值。

self.callGrammerCheckAPI(ForText: """
    ALSO BY STEPHEN HAWKING
    A Brief History of Time
    A Briefer History of Time
    Black Holes and Baby Universes and Other Essays
    The Illustrated A Brief History of Time
    The Universe in a Nutshell
    FOR CHILDREN
    George's Secret Key to the Universe (with Lucy Hawking)
    George's Cosmic Treasure Hunt (with Lucy Hawking)
    ALSO BY LEONARD MLODINOW
    A Briefer History of Time
    The Drunkard's Walk: How Randomness Rules Our Lives
    Euclid's Window: The Story of Geometry from Parallel Lines to Hyperspace
    Feynman's Rainbow: A Search for Beauty in Physics and in Life
    FOR CHILLDRAN
    The Last Dinosaur (with Matt Costello)
    Titanic Cat (with Matt Costello)
""")

这是我正在调用的方法。

func callGrammerCheckAPI(ForText text:String) -> Void {
    var valueToValidate = (text.components(separatedBy: .whitespacesAndNewlines).joined(separator: "+"))

    let url = "https://montanaflynn-spellcheck.p.rapidapi.com/check/?text=\(valueToValidate)"

    let headers: HTTPHeaders = [
        "X-RapidAPI-Key": "3LlMwHr729mshN6RendH4kjvVp1pp1ogORZjsng5F2pBZdjsL3"
    ]
    Alamofire.request(url, headers: headers).responseJSON { response in
        print("Request: \(String(describing: response.request))")   // original url request
        print("Response: \(String(describing: response.response))") // http url response
        print("Result: \(response.result)")                         // response serialization result
         let attributedText = NSMutableAttributedString.init(string: text)
        switch response.result{
        case .success(let returnValue):
            print(returnValue)
            if let valueToParse = returnValue as? [String:Any]{
                if let correctionsFound = valueToParse["corrections"] as? [String:Any]{
                    attributedText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.black, range: NSRange.init(location: 0, length: attributedText.string.utf16.count))
                    for key in correctionsFound.keys{
                        let unwantedCharRegex = try! NSRegularExpression.init(pattern: "([(/\')])", options: NSRegularExpression.Options.caseInsensitive)
                        let formatedKey = unwantedCharRegex.stringByReplacingMatches(in: key, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSRange.init(location: 0, length: key.count), withTemplate: "")
                        let expression = "(\(formatedKey))."
                        let regex = try! NSRegularExpression.init(pattern: expression , options: NSRegularExpression.Options.caseInsensitive)
                        let matches = regex.matches(in: attributedText.string, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSRange.init(location: 0, length: attributedText.string.utf16.count))
                        outerloop: for result in matches{
                            guard let availableOptions = correctionsFound[key] as? [String] else{
                                return
                            }
                            let valueToFound:NSString = NSString.init(string: attributedText.string.subString(from: result.range.location, to: result.range.location+result.range.length))
                            for suggestion in availableOptions{
                                let leftValue:NSString = NSString.init(string: suggestion)
                                let rightValue:NSString = valueToFound
                                print("\(leftValue) == \(rightValue) = \(leftValue == rightValue)")

                                if (leftValue == rightValue) == true {
                                    print("Continue Done")
                                    continue outerloop
                                }
                            }
                            attributedText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: result.range)
                        }
                    }
                }
            }
            break
        case .failure(let error):
            print(error)
            break
        }

        OperationQueue.main.addOperation {
            self.tvReference.attributedText = attributedText
            self.navigationItem.prompt = nil
        }

        if let json = response.result.value {
            print("JSON: \(json)") // serialized json response
        }

        if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
            print("Data: \(utf8Text)") // original server data as UTF8 string
        }
    }
}

问题是当我比较leftValue和rightValue时,即使两个值相同,也会返回false。我不知道那里出了什么问题。

0 个答案:

没有答案