gpt4 book ai didi

swift - 从 do-catch 语句返回字符串

转载 作者:行者123 更新时间:2023-12-03 09:29:30 24 4
gpt4 key购买 nike

我试图将代码从 swift 2 转换为 swift 4 并遇到了这个错误

Errors thrown from here are not handled



所以我这样做了,但现在它告诉我返回一个字符串。知道如何做到这一点吗?
func formatSentence(sentence:String) -> String
{
do {
let regex = try NSRegularExpression(pattern: "\\W+", options: .caseInsensitive)
let modifiedString = regex.stringByReplacingMatches(in: sentence, options: [], range: NSRange(location: 0,length: sentence.count), withTemplate: "")

} catch {
print(error)
}

//I tried adding it here the return modifiedString but gives me error
}

这是原始函数的样子
func formatSentence(sentence:String) -> String
{
let regex = NSRegularExpression(pattern: "\\W+", options: .caseInsensitive)//NSRegularExpression(pattern:"\\W+", options: .CaseInsensitive, error: nil)
let modifiedString = regex.stringByReplacingMatches(in: sentence, options: [], range: NSRange(location: 0,length: sentence.count), withTemplate: "")

return modifiedString
}

最佳答案

这取决于您希望如何处理错误情况。有几个选项:

  • 你可以让它返回 String? ,其中 nil表示有错误:
    func formatSentence(_ sentence: String) -> String? {
    do {
    let regex = try NSRegularExpression(pattern: "\\W+", options: .caseInsensitive)
    let range = NSRange(sentence.startIndex..., in: sentence)
    return regex.stringByReplacingMatches(in: sentence, range: range, withTemplate: "")
    } catch {
    print(error)
    return nil
    }
    }

    然后你会做这样的事情:
    guard let sentence = formatSentence(string) else { 
    // handle error here
    return
    }

    // use `sentence` here
  • 您可以将函数定义为 throws如果遇到一个错误:
    func formatSentence(_ sentence: String) throws -> String {
    let regex = try NSRegularExpression(pattern: "\\W+", options: .caseInsensitive)
    let range = NSRange(sentence.startIndex..., in: sentence)
    return regex.stringByReplacingMatches(in: sentence, range: range, withTemplate: "")
    }

    然后你会在调用点捕获错误:
    do {
    let sentence = try formatSentence(string)

    // use `sentence` here
    } catch {
    // handle error here
    print(error)
    }
  • 或者,假设你知道你的模式是有效的,你可以使用 try!知道它不会失败:
    func formatSentence(_ sentence: String) -> String {
    let regex = try! NSRegularExpression(pattern: "\\W+", options: .caseInsensitive)
    let range = NSRange(sentence.startIndex..., in: sentence)
    return regex.stringByReplacingMatches(in: sentence, range: range, withTemplate: "")
    }

    然后你可以这样做:
    let sentence = formatSentence(string)

    只有当您以 100% 的置信度知道 NSRegularExpression 时,才使用最后一个模式。鉴于您的正则表达式模式(例如在这种情况下),不会失败。


  • 顺便说一句,你可以解开戈尔迪之结,然后使用 replacingOccurrences.regularExpression选项:
    func formatSentence(_ sentence: String) -> String {
    return sentence.replacingOccurrences(of: "\\W+", with: "", options: .regularExpression)
    }

    关于swift - 从 do-catch 语句返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48312991/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com