Swift

Swift

Made by DeepSource

try! statements should be avoided SW-W1008

Bug risk
Major

Force tries in Swift should be avoided as they can lead to runtime errors and make error handling difficult. Force tries are denoted by using a try! statement before a throwing function call. It basically makes an assertion that although the function has the ability to throw an error, it will not throw in this particular scenario and you want to skip the error handling.

Force tries are considered a risky practice as they rely on assumptions about the behavior of the code. If the underlying function changes its behavior or starts throwing errors, the force try can lead to unexpected issues. It is always recommended to use proper error handling mechanisms like do-try-catch or optional binding to handle errors in a safe and predictable manner.

Bad Practice

func fetchData() throws -> Data {
  // Some code that can throw an error
}

func processResponse() {
  let data = try! fetchData() // Force try
  // Process the data
}

Recommended

func fetchData() throws -> Data {
  // Some code that can throw an error
}

func processResponse() {
  do {
    let data = try fetchData() // Proper error handling
    // Process the data
  } catch {
    // Handle the error appropriately
  }
}