【发布时间】: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