【问题标题】:How do I pass arguments to an objects function without a crash如何在不崩溃的情况下将参数传递给对象函数
【发布时间】:2018-03-14 21:06:08
【问题描述】:

我正在尝试将viewController 的逻辑移动到view model,但由于某种原因它总是崩溃,说unexpectedly found nil while unwrapping an Optional value。无论我尝试移动什么代码,我都会经常收到这个错误,所以我一定是在做一些根本错误的事情。这是我在viewController 中的代码示例:

var recipesViewModel: RecipesViewModel! //VIEW MODEL CLASS REFERENCE


var recipeCategory = recipesViewModel.transformToUpperCase(dataRecieverStringRecipeView: "testString")

然后在view modelclass:

func transformToUpperCase(dataRecieverStringRecipeView: String) -> String {
    var recipeCategory = dataRecieverStringRecipeView
    var prefixRecipeCategory = recipeCategory.prefix(1).uppercased()
    var dropFirstRecipeCategory = recipeCategory.dropFirst()
    var upperCasedRecipeCategory = prefixRecipeCategory + dropFirstRecipeCategory
    return upperCasedRecipeCategory
}

...它将字符串转换为第一个字母为大写字母。

当一切都在view model 中时,代码工作得非常好,但是一旦我将它移到另一个类并通过它崩溃的对象调用函数。我错过了什么?

【问题讨论】:

  • 你在实例化一个对象吗? var recipesViewModel:RecipesViewModel!不会创建新对象。
  • 顺便说一句,这是一个很好的例子,说明了为什么最好尽可能避免使用! 强制展开,因为它迫使您处理对象可能不存在(或强制您做出确定确实存在)

标签: swift xcode function object arguments


【解决方案1】:

您需要修复您的视图模型类引用

要更改的行:

var recipesViewModel: RecipesViewModel!

替换线:

var recipesViewModel = RecipesViewModel()

这行代码将正确声明/创建recipesViewModel 作为RecipesViewModel 类的对象。

希望能解决您的问题!

【讨论】:

    【解决方案2】:

    var recipesViewModel: RecipesViewModel! 不实例化新对象。将类别函数放回您的 RecipesViewModel 类中,然后将变量声明更改为:

    声明

    var recipesViewModel: RecipesViewModel! 
    

    稍后

    recipesViewModel = RecipesViewModel() //or whatever initializer you need.
    

    编辑

    正如 rmaddy 指出的那样:您可能可以放弃 !并使用var recipesViewModel: RecipesViewModel = RecipesViewModel() 代替,如果您没有任何可失败的初始化程序,或者这不是运行时注入的属性,只需将其作为 1-liner:

    var recipesViewModel: RecipesViewModel = RecipesViewModel()
    

    【讨论】:

    • 不需要使用: RecipesViewModel!。即使您确实明确输入了类型,但如果您同时初始化值,使用! 确实毫无意义。
    • @rmaddy 是的,除非他们有一个可失败的初始化程序并且没有告诉我们这件事哈哈。尽量不要在问题中添加许多其他概念。
    • 如果初始化程序是失败的,那么变量应该被声明为可选(?),而不是隐式解包(!)。
    • @rmaddy 如果他们知道它不会失败并且隐式打开它更容易怎么办?人们一直这样做。这并不奇怪。我只是坚持他们如何表达他们最初的问题。你不必向我解释这个。我们不知道上下文。
    • 哦,快!我完全错过了那部分!非常感谢你们所有的帮助,它就像一个魅力! :D 感谢您抽出宝贵时间!
    猜你喜欢
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    相关资源
    最近更新 更多