导入 AVFoundation 时 Ambiguous use of ‘subscript’ 错误
Ambiguous use of ‘subscript’ error when importing AVFoundation
使用 Xcode 7.2 和 Swift 2.1.1
我正在从 .plist 文件中检索数据
该文件包含一系列测验的数据。要检索的测验数据由一个包含 12 个问题的数组和一个对应的包含 12 个多项选择选项的数组(每个选项有 4 个成员)组成。
var quizId = “”
var questions:[String] = []
var answers:[[String]] = []
测验 ID 是在前一个视图控制器的 segue 中传递的。然后在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,当最后两行抛出“下标”错误的歧义使用时。
这是因为导入 AVFoundation 会带来新的下标定义(即 AUAudioUnitBusArray,谢谢 Martin R。)并且它会混淆编译器,它不再知道 dict!.objectForKey(“Questions”)
是什么类型(它确实被推断为导入后的 AnyObject,而不是 NSArray)。
解决方法是安全地帮助编译器了解类型,例如通过使用可选绑定进行向下转换:
if let questions = dict?.objectForKey("Questions") as? NSArray {
print(questions[0])
}
甚至更好:
if let questions = dict?.objectForKey("Questions") as? [String] {
print(questions[0])
}
使用 Xcode 7.2 和 Swift 2.1.1
我正在从 .plist 文件中检索数据 该文件包含一系列测验的数据。要检索的测验数据由一个包含 12 个问题的数组和一个对应的包含 12 个多项选择选项的数组(每个选项有 4 个成员)组成。
var quizId = “”
var questions:[String] = []
var answers:[[String]] = []
测验 ID 是在前一个视图控制器的 segue 中传递的。然后在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,当最后两行抛出“下标”错误的歧义使用时。
这是因为导入 AVFoundation 会带来新的下标定义(即 AUAudioUnitBusArray,谢谢 Martin R。)并且它会混淆编译器,它不再知道 dict!.objectForKey(“Questions”)
是什么类型(它确实被推断为导入后的 AnyObject,而不是 NSArray)。
解决方法是安全地帮助编译器了解类型,例如通过使用可选绑定进行向下转换:
if let questions = dict?.objectForKey("Questions") as? NSArray {
print(questions[0])
}
甚至更好:
if let questions = dict?.objectForKey("Questions") as? [String] {
print(questions[0])
}