Search code examples
iosobjective-cswiftmacosnsfilewrapper

Convert [NSFileWrapper initDirectoryWithFileWrappers] to Swift


I have following Objective-C code:

NSFileWrapper* fileWrapper;
NSMutableDictionary* wrappers = [NSMutableDictionary dictionary];
...
fileWrapper = [[NSFileWrapper alloc]
                   initDirectoryWithFileWrappers:wrappers];

I tried to convert above code to Swift:

var fileWrapper : NSFileWrapper?
let wrappers = NSMutableDictionary(dictionary: [:])
....
fileWrapper = NSFileWrapper(directoryWithFileWrappers: wrappers)

the last line cannot be compiled. I got error message saying

Cannot convert value type of 'NSMutableDictionary' to expected argument type '[String : NSFileWrapper]'

I am not sure what is type of [String : NSFileWrapper], a list? Is there anyway to convert wrappers to this type?


Solution

  • The NSFileWrapper initializer has changed to take in a Swift dictionary rather than an NSDictionary:

    public class NSFileWrapper : NSObject, NSCoding {
    
        // ....
    
        public init(directoryWithFileWrappers childrenByPreferredName: [String : NSFileWrapper])
    
        // ....
    }
    

    [String : NSFileWrapper] is Swift syntax for a dictionary where String is the type of the key and NSFileWrapper is the type of the value for that key.

    Just use Swift types:

    Swift 3:

    FileWrapper(directoryWithFileWrappers: [:])
    

    Swift 2.x:

    var fileWrapper : NSFileWrapper?
    let wrappers: [String : NSFileWrapper] = [:]
    fileWrapper = NSFileWrapper(directoryWithFileWrappers: wrappers)