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

前端 未结 2 1891
眼角桃花
眼角桃花 2020-12-16 09:44
func loadThumbnails() {

    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
           


        
2条回答
  •  情深已故
    2020-12-16 10:50

    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)!
    

提交回复
热议问题