Freedlun Freedlun - 1 year ago 117
Swift Question

Ambiguous use of 'subscript' while appending array in Swift 2.2

I had to take a few months away from coding and I'm trying to get my apps up to date. After opening this project in Xcode 7.3 I am getting the "Ambiguous use of 'subscript'" error on this line:

words.append(storedWords[i] as! String)

The whole statement is here:

@if let storedWords : AnyObject = NSUserDefaults.standardUserDefaults().objectForKey("customWords") {
words = []
for var i = 0; i < storedWords.count; ++i {
words.append(storedWords[i] as! String)

I have seen a few similar questions but the are dealing similar. but different situations. I have tried adapting many of those suggestions, but don't see a direct application to this code. If I am wrong, please point me in the right direction.

This code all worked perfectly before the update and I'm sure its a simple syntax adjustment due to Swift 2.2, but so far nothing has worked.

Thank you.

Answer Source

This appears to be due to the use of AnyObject. You probably want to use

if let storedWords = NSUserDefaults.standardUserDefaults().objectForKey("customWords") as? [String] {
    words = [String]()
    for word in storedWords {

Thus pulling the stored words out of user defaults as an array of strings and iterating over them safely knowing that they must all be strings.

However if this is all you are doing, you can simplify greatly to:

let words = NSUserDefaults.standardUserDefaults().objectForKey("customWords") as? [String] ?? []

Which will set words to the array of strings if they exist, otherwise an empty array, no need to iterate just to add all the elements to a new array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download