DAY 29
0
Mobile Development

## 實作

• 在 RecipeDetailView 中 增加 Picker 並選用 segment style

• 更改 ingredient 數據

這段 code 就顯示 RecipeDetailView 中的 ingredient 數據，
因為我們要做一些數學運算才可以得出不同份數的 ingredients，
因為這些運算在其他地方也可能用到，
所以放在管理邏輯的 ViewModel 裡。
1. 宣告 getPortion method
並宣告為靜態方法：
2. 進入 RecipeDetailView 修改 ingredients
3. ingredient portion
新建一個 group 放入算法：

具體的計算份量的 function 內容：
``````static func getPortion(ingredient:Ingredients, recipeServings:Int, targetServings: Int ) -> String {
var portion = ""
var numerator = ingredient.num ?? 1
var denominator = ingredient.denom ?? 1
var wholePortion = 0
if ingredient.num != 0 {
denominator *= recipeServings
numerator *= targetServings
let divisor = Rational.greatestCommonDivisor(numerator, denominator)
numerator /= divisor
denominator /= divisor
if numerator >= denominator  {
wholePortion = numerator / denominator
numerator = numerator % denominator
portion += String(wholePortion)
}
if numerator > 0 {
portion += wholePortion > 0 ? " " : ""
portion += "\(numerator)/\(denominator)"
}

}
if let unit = ingredient.unit {
portion += ingredient.num == nil && ingredient.denom == nil ? "" : " "
return portion + unit
}

return portion
}

``````

``````if var unit = ingredient.unit {
if wholePortion > 1 {
if unit.suffix(2) == "ch" {
unit += "es"
}
else if unit.suffix(1) == "f" {
unit = String(unit.dropLast())
unit += "ves"
}
else {
unit += "s"
}
}
portion += ingredient.num == nil && ingredient.denom == nil ? "" : " "
return portion + unit
}
``````