在Swift中使用Do / Catch

时间:2017-07-06 10:14:34

标签: swift

我正在开发一款应用,希望从某个功能中获取数据。但是,有时数据丢失或与我想要检索的数据不同。我是Swift的新手,我找不到一种方法来编写一个执行一些处理并返回此数据的函数。当缺少此数据时,该函数应该返回一个字符串“Not Found”。像这样:

func processData(data:String) {
    do {
        //processing
        var result = processedData
    } catch {
        var result = "Not Found"
    }

    return result
}

如果有人能帮助我,那将是非常好的。

5 个答案:

答案 0 :(得分:4)

您应该检查result是否为零。

func processData(data: String?) -> String {
    guard let result = data else {
        return "Not Found"
    }

    return result
}

答案 1 :(得分:1)

最简洁的方法是使用guard-let构造:

func processData(data: String?) -> String {
    // Assuming getProcessedData(:) returns your processed data
    guard let result = getProcessedData(data) else {
        return "Not found"
    }
    return result
}

此外,您的函数缺少返回类型。您必须在返回某些值的所有函数中指定返回类型,如-> TYPE

答案 2 :(得分:0)

swift的一个好习惯是正确使用投掷错误

这是一个受你的启发的例子:

enum Errors: Error {
  case noData
  case unknownError
}

func progress(data: String?) throws -> String {

  guard let data = data else {
    // Data is missing
    throw Errors.noData
  }

  // Do other things, and throw if necessary

  result = data

  return result
}

do {
  try process(data: "A data to process")
} catch {
  print("An error occurred: \(error)")
}

您可以在Swift Playgound中尝试此代码

答案 3 :(得分:0)

您的功能需要明确指出<a href="https://twitter.com/" class="fa-twitter" target="_blank" onclick="trackOutboundLink('https://twitter.com/'); return false;">Twitter</a> /usr/local/bin/forever也适用于可能引发错误的方法。看来你需要看看如何使用选项。期权可以有价值,也可以没有价值。

Page1.page1.LV1.Select();

答案 4 :(得分:0)

这些答案都写到我的是正确的。有一种方法:使用处理程序检查获得结果并按你的观点使用。

enum Errors: Error {
  case noData
  case unknownError
}

func progress(data: String?, completionHandler: @escaping (_ result: String? , _ error: Error?) -> Void ) {

  guard let data = data else {
    // Data is missing
    throw nil, Errors.noData
  }

  // Do other things, and throw if necessary

  result = data

  return result, nil
}

// example of calling this function 
process(data: "A data to process"){(result, error) -> Void in 
     //do any stuff
     /*if error == nil {
     }*/
}