ios - 返回一个对象“没有更多上下文的表达式类型不明确”
问题描述
我想返回我的 RecipeModel 对象,但收到“表达式类型不明确,没有更多上下文”的错误。我确实使用了我在结构中创建的所有属性。我已经尝试删除 ",json:[String: Any]" 并检查是否错过了括号。我错过了什么?谢谢你的帮助。
func parseRecipes(forJSON json: [String: Any]) -> [RecipeModel] {
guard let recipesData = json["recipeTiles"] as? [[String: Any]] else { return [] }
let recipes = recipesData.compactMap({ (recipesDictionary) -> RecipeModel? in
let recipeTypeString = recipesDictionary["type"] as? String
let imageString = recipesDictionary["image"] as? String
let bgTypeString = recipesDictionary["backgroundType"] as? String
let bgType = BackgroundType(rawValue: bgTypeString ?? "")
let title = recipesDictionary["title"] as? String
let ingredients = recipesDictionary["ingredients"] as? [[String: String]]
let directions = recipesDictionary["directions"] as? [[String: String]]
return RecipeModel(type: recipeTypeString, image: imageString, title: title, ingredients: ingredients, directions: directions, bgType: bgType) // Error pops up here
})
return recipes
}
这是我的 RecipeModel 结构,其中列出了所有 let 属性
struct RecipeModel {
var viewMode: CardViewMode = .card
var type: String
var title: String
var ingredients: [IngredientModel]
var directions: [DirectionModel]
var image: String
var backgroundType: BackgroundType = .light
init(type: String, title: String, ingredients: [String: Any], directions: [String: Any], image: String, bgType: BackgroundType, json: [String: Any]) {
self.type = type
self.title = title
self.image = image
self.backgroundType = bgType
self.ingredients = []
if let jsonIngredients = json["ingredients"] as? [String: Any] {
for jsonIngredient in jsonIngredients {
self.ingredients.append(IngredientModel(json: jsonIngredient as? [String: Any] ?? [:]))
}
}
self.directions = []
if let jsonDirections = json["directions"] as? [String: Any] {
for jsonDirections in jsonDirections {
self.directions.append(DirectionModel(json: jsonDirections as? [String: Any] ?? [:]))
}
}
}
}
解决方案
初始化器是一个函数。函数声明是一个契约。当您调用该函数时,您必须保留该合同。我很欣赏这不是一个非常有用的错误消息,可能值得提交一个错误报告,但实际错误的性质非常简单。
因此,错误出现在您调用 RecipeModel 初始化程序的行,如下所示:
RecipeModel(type: recipeTypeString, image: imageString, title: title, ingredients: ingredients, directions: directions, bgType: bgType)
好吧,没有这样的初始化程序。初始化程序是这样的:
init(type: String, title: String, ingredients: [String: Any], directions: [String: Any], image: String, bgType: BackgroundType, json: [String: Any]) {
您的调用必须包含所有这些参数。它们必须按照那个顺序(type:
,然后title:
- 你已经放image:
了 - 等等)并且它不能省略它们中的任何一个(你已经json:
完全省略了)。(编辑当然传递参数的类型必须与相应参数的声明类型匹配。)
推荐阅读
- haskell - 你能帮我理解 Haskell 中 foldr 的实现类型吗?
- python - 使用 simpledbf 忽略备注字段
- d3.js - d3.js 更新数据绑定失败
- flutter - Password show/hide toggle deletes password TextField value (Flutter)
- dataweave - 数据编织中的复杂操作
- c# - 如何访问 Android 模拟器中的本地文件夹以检索 SQLite 数据库?
- c++ - 如果我写的太多,C++ fstream 在关闭文件时抛出异常
- php - 启用 wordpress 多站点会中断数据库连接
- gitlab - Gitlab Sonar Qube 重定向网址
- python - 使用插值重新索引 Pandas DataFrame