28
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”

这是什么意思?

谁能帮帮我,谢谢!!!!

4

2 回答 2

50

Apple 在The Swift Programming Language中声明:

for-in 循环为范围、序列、集合或进程中的每个项目执行一组语句。

现在,directoryContent只是符合协议AnyObject,所以你不能在它上面使用 for 循环。如果你想这样做,你必须做类似下面的事情:

for item in directoryContent as [AnyObject] {
    //Do stuff
}
于 2014-08-29T07:48:53.310 回答
5

contentsOfDirectoryAtPath返回一个NSArray,而您将其转换为AnyObject. 解决方案是将其转换为[AnyObject]?or 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)!
于 2014-08-29T07:53:25.517 回答