Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 从do catch语句返回字符串_Swift_Do Catch - Fatal编程技术网

Swift 从do catch语句返回字符串

Swift 从do catch语句返回字符串,swift,do-catch,Swift,Do Catch,我试图将代码从swift 2翻译成swift 4,但遇到了这个错误 不会处理从此处抛出的错误 我这样做了,但现在它告诉我返回一个字符串。你知道怎么做吗 func formatSentence(sentence:String) -> String { do { let regex = try NSRegularExpression(pattern: "\\W+", options: .caseInsensitive) let modifiedStrin

我试图将代码从swift 2翻译成swift 4,但遇到了这个错误

不会处理从此处抛出的错误

我这样做了,但现在它告诉我返回一个字符串。你知道怎么做吗

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
}

在函数开头设置默认值,如下所示:

func formatSentence(sentence:String) -> String {
   var regex = ""
   var modifiedString = "" 

   do {
       regex = try NSRegularExpression(pattern: "\\W+", options: .caseInsensitive)
       modifiedString = regex.stringByReplacingMatches(in: sentence, options: [], range: NSRange(location: 0,length: sentence.count), withTemplate: "")

   } catch {
       print(error)
   }
   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
    
  • 您可以将函数定义为在遇到错误时抛出该错误的函数:

    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)
    }
    

    你只需要返回一个字符串:
    returnmodifiedstring
    @vadian是的,但它不让我知道它说了什么?你是什么意思?您是否尝试添加该行代码?您可能需要在do/catch之外初始化字符串,如var response=“”,并将其返回。然后,您可以指定response=modifiedString或response=error,以在抛出错误时返回错误。创建
    NSRange
    时,传递
    字符串
    utf16 count
    NSRange(位置:0,长度:句子.utf16.count)
    或将
    字符串
    强制转换为
    NSString
    并传递其
    长度
    另一个选项是使用新的Swift 4初始值设定项
    init(u region:R,in target:S),其中R:RangeExpression,S:StringProtocol,R.Bound==String.Index,S.Index==String.Index
    Range
    转换为
    NSRange
    NSRange(句子.startIndex..我专注于抛出
    NSRegularExpression
    和返回字符串,但你是对的。我相应地更新了我的示例。正如我在回答结束时所说,他真的应该只使用
    replacingOccurrences(of:with:options:)
    ,并彻底消除所有这些愚蠢之处。我在Rob的回答中发表的评论与下面的帖子一样适用于这里,这是一个坏主意。从错误中返回有效的内容意味着在另一端,您必须检查
    modifiedString
    是否不是空的,并且变得不必要的复杂