给RecipeModel中的方法中的int到int的方法[复制]

问题描述 投票:0回答:2

这个问题在这里已有答案:

Ciao大家,我是Swift的新手,我将一些变量从String转换为Int到方法调用'newRecipe'有些麻烦。我试过这个解决方案,但我不知道如何将新值放在代码中。有人请帮帮我?非常感谢!

// Method to create a recipe
func newRecipe(titleRecipe: String, recipeTime: String, peopleRecipe: String, preparationTime: String, cookingTime: String, bakingTempRecipe: String, imageRecipe: UIImage)
{
    let newRecipe = RecipeModel(titleRecipe: titleRecipe,
                                recipeTime: recipeTimeInt,
                                peopleRecipe: peopleRecipe,
                                preparationTime: preparationTime,
                                cookingTime: cookingTime,
                                bakingTempRecipe: bakingTempRecipe,
                                imageRecipe: imageRecipe)

    // Make the var from String into Int
    // To calculate the value of recipeTime from addition of preparationTime and cookingTime
    if var recipeTimeInt = Int(recipeTime)
    {
        let preparationTimeInt = Int(preparationTime)
        let cookingTimeInt = Int(cookingTime)
        recipeTimeInt = preparationTimeInt! + cookingTimeInt!
    }

    recipes.append(newRecipe)
    salva()

    // reload the collection of recipeController
        recipeController?.collectionView!.reloadData()
}
swift string int
2个回答
2
投票

你应该写那样的东西.. ??是这样,如果它不能将参数转换为Int,它将为您的变量myInt添加0 ..

let myInt:Int = Int("1234") ?? 0

0
投票

你可以通过创建String的扩展来实现这一点:

extension String {
  var toInt: Int {
    return Int(self) ?? 0
  }
}

并像这样使用它

let preparationTimeInt = preparationTime.toInt
© www.soinside.com 2019 - 2024. All rights reserved.