Type 'AnyObject' does not conform to protocol 'SequenceType'

戏子无情 提交于 2019-11-30 07:19:44

问题


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
        }
    }
}

the compile error is below:

Type 'AnyObject' does not conform to protocol 'SequenceType'

what does this menas?

who can help me ,thks a lot!!!!


回答1:


Apple states in The Swift Programming Language:

The for-in loop performs a set of statements for each item in a range, sequence, collection, or progression.

Right now, directoryContent is just conforming to protocol AnyObject, so you can't use for loops over it. If you want to do so, you have to do something similar to the following:

for item in directoryContent as [AnyObject] {
    //Do stuff
}



回答2:


contentsOfDirectoryAtPath returns an NSArray, whereas you are casting it to AnyObject. The solution is to cast it to either [AnyObject]? or NSArray:

let directoryContent: [AnyObject]? = fileManager.contentsOfDirectoryAtPath(documentsDirectory, error: &error)

or

let directoryContent: NSArray? = fileManager.contentsOfDirectoryAtPath(documentsDirectory, error: &error)

Then use an optional binding before the for loop:

if let directoryContent = directoryContent {
    for item:AnyObject in directoryContent {

Looking at the contentsOfDirectoryAtPath documentation, it states it always returns an array - so what said above can be reduced to unwrapping the return value to either a swift or objc array, with no need to use the optional binding:

let directoryContent: [AnyObject] = fileManager.contentsOfDirectoryAtPath(documentsDirectory, error: &error)!

or

let directoryContent: NSArray = fileManager.contentsOfDirectoryAtPath(documentsDirectory, error: &error)!


来源:https://stackoverflow.com/questions/25563655/type-anyobject-does-not-conform-to-protocol-sequencetype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!