问题
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