2

I am working with Swift, using a dictionary, and then trying to put info into an array, and access values in the array. This is what I have in my code:

// I have abbreviated the actual dictionary to not waste question space...
var plateIssuers: Dictionary<String,String> = [
    "Alberta": "Canada",
    "British Columbia": "Canada",
    "Manitoba":"Canada",
    "VERMONT":"USA",
    "WASHINGTON":"USA",
    "WISCONSIN":"USA",
    "WEST VIRGINIA":"USA",
    "WYOMING]":"USA"]

// This is an attempt that seems to work to create an Array of unique values (turning into sets and then back to array
let countries:Array = NSSet(array: Array<String>(plateIssuers.values)).allObjects
let issuers:Array = NSSet(array: Array<String>(plateIssuers.keys)).allObjects

Later, in a tableView function, I have the following code:

println(countries[1])
cell.textLabel.text = countries[(indexPath.row)]

The println works fine (prints "Canada"), but the cell.textLabel line gives the following error (won't build):

Could not find an overload for 'subscript' that accepts the supplied arguments

How can the println work but not the next line. I should also mention that the second line works if I just refer to an array I built in a simple manner with strings in it. Is my problem the way I created the "countries" array? or is it a problem in how I am referencing it? Thanks

3
  • try remove parentheses. i.e. countries[indexPath.row] Commented Jul 6, 2014 at 23:45
  • Thanks, but that's how I had it originally. I put them in to see if it would help, which it didn't. Commented Jul 6, 2014 at 23:46
  • 2
    The problem is that you are typing countries too loosely. You must type it as Array<String>: in particular, you must cast the result of allObjects to Array<String>. Every type in Swift must be extremely specific, and things are not magically downcast for you as they come across the bridge from Objective-C. Commented Jul 6, 2014 at 23:48

1 Answer 1

3

Do this:

let countries = NSSet(array: Array<String>(plateIssuers.values)).allObjects as Array<String>

Swift's compiler as usual is being coy in its expression of the problem. What it means here is that subscripting an array of AnyObject, which is what comes back from allObjects, is possible, but is not going to net you a String, which is what a label's text property expects.

Sign up to request clarification or add additional context in comments.

1 Comment

And I suggest you file a bug about the inadequacy of the compiler error. In general Swift's way of saying "you are not passing on the right side the type that the left side expects" is extremely obscure and generally points the user in the wrong directly entirely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.