Home > front end >  Default integer result to avoid dividing by zero in SwiftUI
Default integer result to avoid dividing by zero in SwiftUI

Time:02-06

How do I create a default 0 value result for a calculated variable when the calculation divides by 0?

I am a beginner in SwiftUI and am trying to create a simple quiz app. In the app, questions by category are counted, such as "hsa" below (hsaCount.correct and hsaCount.incorrect) and eventually a score is calculated (scoreHSA).

The current code below works fine except when an "hsa" question is not attempted which results in "triedHsa" being 0 and an error of "Thread 1: Fatal error: Division by zero"

I am trying to figure out how to make the default scoreHsa result 0 if triedHsa is 0.

I tried using guard and if/else statements but failed, likely due to my inexperience.

let hsaCount: (correct: Int, incorrect: Int)

var triedHsa: Int { hsaCount.correct   hsaCount.incorrect}

var scoreHsa: Int { ((hsaCount.correct * 100) / triedHsa)}

CodePudding user response:

Use ternary expression:

var scoreHsa: Int {
  triedHsa == 0 ? 0 : ((hsaCount.correct * 100) / triedHsa)
}

Or, you can use conditional expressions:

var scoreHsa: Int {
  guard triedHsa != 0 else {
     return 0 
  }

  return (hsaCount.correct * 100) / triedHsa
}

CodePudding user response:

Swift is missing a throwing function for this; you need to make one yourself.

(option / makes ÷)

var scoreHsa: Int { (try? hsaCount.correct * 100 ÷ triedHsa) ?? 0 }
infix operator ÷: MultiplicationPrecedence

public extension BinaryInteger {
  /// - Throws: `DivisionByZeroError<Self>`
  static func ÷ (numerator: @autoclosure () -> Self, denominator: Self) throws -> Self {
    guard denominator != 0
    else { throw DivisionByZeroError() }

    return numerator() / denominator
  }
}

public struct DivisionByZeroError: Error { }
  •  Tags:  
  • Related