Swift视图间传递字典数组后,视图B取值出现编译错误的解决咨询
解决Swift字典数组传递后的索引访问错误
问题根源
你混淆了数组和字典的API用法:
bookOptions是[[String:Any]]类型,也就是字典数组,不是单个字典。index(forKey:)是Dictionary专属方法,用于查找字典中某个key对应的索引;而数组的index(where:)需要传入闭包来判断元素是否符合条件,不能直接传入字符串。
修正方案
根据需求,有两种常见处理方式:
1. 遍历数组中所有字典,提取指定key的值
如果需要处理数组里的每一个字典,直接遍历数组,对每个字典用下标访问key:
struct ShowBlindDateChoices: View { @Binding public var bookOptions: [[String:Any]] var body: some View { VStack{ // 遍历数组中的每个字典,提取"synopsis"对应的值 for bookDict in bookOptions { if let synopsis = bookDict["synopsis"] { print("synopsis:", synopsis) } } } } }
2. 查找数组中第一个包含指定key的字典
如果只需要找到数组中第一个包含"synopsis"的字典,使用数组的first(where:)方法:
struct ShowBlindDateChoices: View { @Binding public var bookOptions: [[String:Any]] var body: some View { VStack{ // 找到第一个包含"synopsis"的字典 if let targetBook = bookOptions.first(where: { $0.keys.contains("synopsis") }), let synopsis = targetBook["synopsis"] { print("First synopsis:", synopsis) } } } }
额外提示
视图A中跳转的目标是ShowBookChoices,但视图B的结构体名是ShowBlindDateChoices,这是笔误,需要保持一致,否则会导致编译错误。
内容的提问来源于stack exchange,提问作者user1233894
相关产品推荐
相关产品推荐

