2

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?

JAL
  • 41,701
  • 23
  • 172
  • 300
David.Chu.ca
  • 37,408
  • 63
  • 148
  • 190

1 Answers1

4

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)
JAL
  • 41,701
  • 23
  • 172
  • 300
  • Not much point declaring a constant for an empty dictionary literal. Just do FileWrapper(directoryWithFileWrappers: [:]) (the NS was removed in Swift 3) – Ash Jan 29 '17 at 09:20
  • @Ash Thanks this was an old answer written in Swift 2.x to match the asker. Updated the answer to Swift 3. – JAL Feb 24 '17 at 16:19