这个问题在这里已有答案:
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()
}
你应该写那样的东西.. ??是这样,如果它不能将参数转换为Int,它将为您的变量myInt添加0 ..
let myInt:Int = Int("1234") ?? 0
你可以通过创建String的扩展来实现这一点:
extension String {
var toInt: Int {
return Int(self) ?? 0
}
}
并像这样使用它
let preparationTimeInt = preparationTime.toInt