[英]Ambiguous use of 'subscript' - NSMutableDictionary
My code worked perfectly in the version of Swift in May 2015, when I programmed the app. 当我编写应用程序时,我的代码在2015年5月的Swift版本中运行良好。 When I opened XCode 7.2 today I get an odd error message I can't understand: Ambiguous use of 'subscript'.
今天,当我打开XCode 7.2时,收到一条奇怪的错误消息,我无法理解:'subscript'的用法不明确。 In total I get this error 16 times in my code, do anyone know what I can change to fix this problem?
总共我的代码中出现16次此错误,有人知道我可以更改以解决此问题吗?
if let path = NSBundle.mainBundle().pathForResource("colorsAndAlternatives", ofType: "plist") {
if let dict = NSMutableDictionary(contentsOfFile: path) {
let randomNumber = Int(arc4random_uniform(UInt32(numberOfOptions)))
let correctColor = "#" + String(dict["\(randomNumber)"]![1] as! Int!, radix: 16, uppercase: true) // Ambiguous use of 'subscript'
The correctColor is determined by HEX using this code: https://github.com/yeahdongcn/UIColor-Hex-Swift/blob/master/HEXColor/UIColorExtension.swift 正确的颜色由十六进制使用以下代码确定: https : //github.com/yeahdongcn/UIColor-Hex-Swift/blob/master/HEXColor/UIColorExtension.swift
The Swift compiler is much more strict now. Swift编译器现在更加严格。
Here, it doesn't know for sure what type is the result of dict["\\(randomNumber)"]
so it bails and asks for precisions. 在这里,它不确定
dict["\\(randomNumber)"]
的结果是什么类型,因此它dict["\\(randomNumber)"]
并要求精度。
Help the compiler understand that the result is an array of Ints and that you can access it alright with subscript, for example: 帮助编译器了解结果是一个Ints数组,您可以使用下标直接访问它,例如:
if let result = dict["\(randomNumber)"] as? [Int] {
let correctColor = "#" + String(result[1], radix: 16, uppercase: true)
}
Here's my attempt to unwrap what's going on: 这是我尝试展开的事情的尝试:
if let path = NSBundle.mainBundle().pathForResource("colorsAndAlternatives", ofType: "plist") {
if let dict = NSMutableDictionary(contentsOfFile: path) {
let randomNumber = Int(arc4random_uniform(UInt32(numberOfOptions)))
let numberKey = "\(randomNumber)"
if let val = dict[numberKey] as? [AnyObject] { // You need to specify that this is an array
if let num = val[1] as? NSNumber { // If your numbers are coming from a file, this is most likely an array of NSNumber objects, since value types cannot be stored in an NSDictionary
let str = String(num.intValue, radix: 16, uppercase: true) // construct a string with the intValue of the NSNumber
let correctColor = "#" + str
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.