func loadThumbnails() {
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentsDirectory:NSString = paths[0] as NSString
var error:NSError?
let fileManager = NSFileManager()
let directoryContent:AnyObject = fileManager.contentsOfDirectoryAtPath(documentsDirectory, error: &error)!
thumbnails = [QSPhotoInfo]()
for item:AnyObject in directoryContent {
let fileName = item as NSString
if fileName.hasPrefix(kThumbnailImagePrefix) {
let image = loadImageFromDocumentsDirectory(fileName)
var photoInfo = QSPhotoInfo()
photoInfo.thumbnail = image;
photoInfo.thumbnailFileName = fileName
thumbnails += photoInfo
}
}
}
编译错误如下:
类型'AnyObject'不符合协议'SequenceType'
这个menas是什么?
谁能帮帮我,很多!!!!
答案 0 :(得分:46)
Apple在The Swift Programming Language中声明:
for-in循环为范围中的每个项执行一组语句, 序列,集合或进展。
现在,directoryContent
只是符合协议AnyObject
,所以你不能在它上面使用for循环。如果你想这样做,你必须做类似以下的事情:
for item in directoryContent as [AnyObject] {
//Do stuff
}
答案 1 :(得分:4)
contentsOfDirectoryAtPath
会返回NSArray
,而您将其投放到AnyObject
。解决方案是将其投射到[AnyObject]?
或NSArray
:
let directoryContent: [AnyObject]? = fileManager.contentsOfDirectoryAtPath(documentsDirectory, error: &error)
或
let directoryContent: NSArray? = fileManager.contentsOfDirectoryAtPath(documentsDirectory, error: &error)
然后在for循环之前使用可选的绑定:
if let directoryContent = directoryContent {
for item:AnyObject in directoryContent {
查看contentsOfDirectoryAtPath
文档,它声明它总是返回一个数组 - 所以上面说的可以简化为将返回值解包到swift或objc数组,而不需要使用可选的绑定:
let directoryContent: [AnyObject] = fileManager.contentsOfDirectoryAtPath(documentsDirectory, error: &error)!
或
let directoryContent: NSArray = fileManager.contentsOfDirectoryAtPath(documentsDirectory, error: &error)!