swift - String to Int in to method in a let RecipeModel

标签 swift string int

<分区>

再见大家, 我是 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,它会将 0 添加到您的变量 myInt..

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

关于swift - String to Int in to method in a let RecipeModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49105059/

相关文章:

c++ - 使用 C++ 查找第 1500000 个斐波那契数

ios 快速播放从cloudkit上传的视频

ios - 将 3 种不同的信息加载到 3 种不同类型的细胞

c++ - "to_string"是 't a member of "标准”?

Python — 检查字符串是否包含西里尔字符

c++ - 格式化 : how to convert 1 to “01” , 2 到 “02” , 3 到 "03",等等

ios - 将图像从设备上传到 Firebase

ios - AutoLayout 按钮,渐变,不会调整到高度

Python - Pandas - GroupBy 条件字符串加法

java - 如何读取整数、 double 和字符串并将其保存到变量中?