Ambiguous use of ‘subscript’ error when importing AVFoundation

故事扮演 提交于 2019-12-10 21:16:02

问题


Using Xcode 7.2 and Swift 2.1.1

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]] = []

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]]

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


回答1:


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])
}

or even better:

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


来源:https://stackoverflow.com/questions/34998108/ambiguous-use-of-subscript-error-when-importing-avfoundation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!