Using Do / Catch in Swift

I am working on an application and want to return data from a function. However, sometimes the data are missing or different from the ones I want to receive. I am new to Swift, and I cannot find a way to write a function that processes and returns this data a bit. When this data is missing, the function should return the string "Not Found". Like this:

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

    return result
}

It would be very nice if someone could help me.

+4
source share
5 answers

You have to check if there is any result.

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

    return result
}
+4
source

The most concise way to do this is to use a construct 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 , .

+1

​​

, :

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

0

Your function should be explicitly about returning something, for example. -> StringAlso do-catchintended for methods that may cause an error. Sounds like you need to take a look at how to use advanced options. Options may matter or they may not matter.

fun processData(data: String) -> String {
   var result: String?
   // Do some processing and assign the result to result variable

  guard let result = result else { return "Not Found" }

  return result
}
0
source

These answers were written as long as I am right. There is one way: with a handler check, get the result and use it at your point.

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 {
     }*/
}
0
source

Source: https://habr.com/ru/post/1680875/


All Articles