M4 Lesson 12 Please explain - var numerator = ingredient.num ? 1

Please explain

var numerator = ingredient.num ?? 1

Why we have to assign 1 to ingredient.num if ingredient.num is nil?


Reason has been found; you can not have 0/denominator.

That’s not quite correct. If you look at Recipe.swift…

struct Ingredient: Identifiable, Decodable {
    var id: UUID?
    var name: String
    var num: Int?
    var denom: Int?
    var unit: String?

…you will see that num is declared as Optional so if num is nil then use nil coalescing to provide the value 1.

why 1, not 0

AI got this answer

In the code snippet you provided, denominator is assigned the value of ingredient.denom if it is not null ( ?? is the null-coalescing operator). Otherwise, it is assigned the value 1 .

The reason 1 is used as the default value instead of 0 is because 0 as a denominator would cause a division by zero error, which is generally undesirable in most cases. To avoid this error, a non-zero default value such as 1 is commonly chosen. This ensures that the division operation is always well-defined and avoids potential runtime errors.

By using 1 as the default denominator, if ingredient.denom is null , the division operation will effectively be a division by 1 , which is equivalent to simply using the numerator value alone. This can be useful in various scenarios where a default value is needed, but dividing by zero is not desired.

In the case of the denominator the value can’t be zero since that would cause a division by zero and a crash.

In the example you provided we are talking about num which is the numerator (the value that denominator is divided into). We set it to 1 using the nil coalescing operator because the you can’t have an ingredient quantity of 0.

1 Like

I almost forgot all about fractions. Thanks