ThomasGulli
ThomasGulli

Reputation: 604

Ambiguous use of 'subscript' - NSMutableDictionary

My code worked perfectly in the version of Swift in May 2015, when I programmed the app. When I opened XCode 7.2 today I get an odd error message I can't understand: Ambiguous use of 'subscript'. In total I get this error 16 times in my code, do anyone know what I can change to fix this problem?

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

Upvotes: 1

Views: 710

Answers (2)

JAL
JAL

Reputation: 42449

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

Upvotes: 2

Eric Aya
Eric Aya

Reputation: 70098

The Swift compiler is much more strict now.

Here, it doesn't know for sure what type is the result of dict["\(randomNumber)"] so it bails and asks for precisions.

Help the compiler understand that the result is an array of Ints and that you can access it alright with subscript, for example:

if let result = dict["\(randomNumber)"] as? [Int] {
    let correctColor = "#" + String(result[1], radix: 16, uppercase: true)
}

Upvotes: 3

Related Questions