[英]Cannot subscript a value of type anyobject
I've currently upgraded to the new Xcode 7, and the following code never had any errors with swift 1.2, but now its telling me that : 我目前已升级到新的Xcode 7,以下代码在swift 1.2中从未出现任何错误,但是现在它告诉我:
Cannot subscript a value of type any object
无法下标任何对象类型的值
var imageArray : NSArray = []
let url = NSURL(string: (self.imageArray[indexPath.row][0] as? String)!)
I know its about [0]
but how do i rewrite it to be accepted ? 我知道它的
[0]
但是我该如何重写它才能被接受?
OK, so first you are using an NSArray
. OK,所以首先您要使用
NSArray
。 You can drop that and make everything much easier. 您可以删除它并简化所有操作。
In Swift always use strong typing where possible. 在Swift中,请尽可能使用强类型。 Avoid Any and AnyObject when they are not needed.
不需要时,请避免使用Any和AnyObject。 (They are VERY RARELY needed).
(非常需要它们)。
The error is happening because you're not telling the code what is actually in the imageArray
. 发生错误是因为您没有告诉代码
imageArray
实际包含的imageArray
。
Also, imageArray
tells me the array is full of images. 另外,
imageArray
告诉我数组中充满了图像。 Name your variables more descriptively. 更描述性地命名变量。
imageUrlStringArray
or arrayOfImageUrlArrays
. imageUrlStringArray
或arrayOfImageUrlArrays
。 Something more descriptive anyway. 无论如何,更具描述性。
Declare imageArray
like... 像这样声明
imageArray
...
var imageArray = [[String]]()
This tells the compiler that imageArray
is a 2D array with Strings
at the second level. 这告诉编译器
imageArray
是2D数组,其中Strings
位于第二级。
Now you can create your URL easily... 现在,您可以轻松创建URL ...
guard
let urlString = imageArray[indexPath.row].first,
let url = NSURL(string: urlString)
else { // Handle the inability to create a URL }
// Do something with the url
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.