× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

[AnyObject]?' does not have a member named 'subscript'

Antonio Bello
Mar 01, 2015
<p>The array is declared as:</p> <pre><code> private var items: [AnyObject]? </code></pre> <p>so, as you also said, it's an optional</p> <p>In swift an <code>optional</code> is an enum, so a type on its own - and as an optional, it can contain either a <code>nil</code> value or an object of the contained type.</p> <p>You want to apply the subscript to the array, not to the optional, so before using it you have to unwrap the array from the optional</p> <pre><code>items?[indexPath.row] </code></pre> <p>but that's not all - you also have to use the conditional downcast:</p> <pre><code>as? Activity </code></pre> <p>because the previous expression can evaluate to nil</p> <p>So the correct way to write the if statement is</p> <pre><code>if let act = items?[indexPath.row] as? Activity { </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/25975489/%5BAnyObject%5D?'%20does%20not%20have%20a%20member%20named%20'subscript'/25975911">Stack Overflow</a>.</p>
comments powered by Disqus