导入 AVFoundation 时使用“下标"错误不明确 [英] Ambiguous use of ‘subscript’ error when importing AVFoundation

查看:26
本文介绍了导入 AVFoundation 时使用“下标"错误不明确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Xcode 7.2 和 Swift 2.1.1

Using Xcode 7.2 and Swift 2.1.1

我正在从 .plist 文件中检索数据该文件包含一系列测验的数据.要检索的测验数据由 12 个问题的数组和相应的 12 个多项选择选项数组(每个 4 名成员)组成.

I am retrieving data from a .plist file The file contains data for a series of quizzes. The data for the quiz to be retrieved consists of an array of 12 questions and a corresponding array of 12 multiple choice options (4 members each).

var quizId = ""
var questions:[String] = []
var answers:[[String]] = []

测验 id 是从前一个视图控制器的 segue 中传递的.然后在 ViewDidLoad 中检索数据.

The quiz id is passed in a segue from the previous view controller. Then the data is retrieved in ViewDidLoad.

let path = NSBundle.mainBundle().pathForResource("quiz id", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path!)
questions = dict!.objectForKey("Questions")![0] as! [String]
answers = dict!.objectForKey("Answers")![1] as! [[String]]

代码运行良好,直到我尝试导入 AVFoundation,当最后两行抛出下标"错误使用时.

The code works perfectly well until I try to import AVFoundation, when the last two lines throw the ambiguous use of ‘subscript’ error.

推荐答案

这是因为导入 AVFoundation 会带来新的下标定义(即 AUAudioUnitBusArray,谢谢 Martin R.)并且混淆了不知道类型是什么的编译器dict!.objectForKey(Questions")(导入后确实推断为 AnyObject,而不是 NSArray).

This is because importing AVFoundation brings up new subscript definitions (namely AUAudioUnitBusArray, thank you Martin R.) and it confuses the compiler which doesn't know what type is dict!.objectForKey("Questions") anymore (it is indeed inferred as AnyObject after the import, instead of NSArray).

解决方法是安全地帮助编译器了解类型,例如通过使用可选绑定进行向下转换:

The cure is to safely help the compiler to know the type, for example by doing a downcast with optional binding:

if let questions = dict?.objectForKey("Questions") as? NSArray {
    print(questions[0])
}

甚至更好:

if let questions = dict?.objectForKey("Questions") as? [String] {
    print(questions[0])
}

这篇关于导入 AVFoundation 时使用“下标"错误不明确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆