Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the equivalent of NSArray's writeToFile: atomically: in Swift and Array?

Tags:

swift

cocoa

I've been learning about Swift and building an Cocoa app which is based on Swift, and faced the issue that Swift's built-in Array type doesn't have writeToFile: atomically: method which is implemented in Objective-C's NSArray.

So how can I write the contents of the array to a file? Is there any such method in Swift? (FYI, I wasn't able to find the documentation of the Swift's Array type much like the Objective-C's NSArray. If you did, please link it in comment section.)

Or if it cannot be done to write the content of an array to the file in Swift using the built-in Array, what's the best alternative? I think NSArray is also available in Swift code, but I rather want to avoid Objective-C's classes. Or should I use extension to implement the feature in Array?

like image 703
Blaszard Avatar asked Feb 13 '23 17:02

Blaszard


1 Answers

I am not sure if the "native" ability for writing arrays to files exists in Swift, but since arrays can be bridged to NSArrays, you should be able to write your arrays to a file like this:

let mySwiftArray = ... // Your Swift array
let cocoaArray : NSArray = mySwiftArray
cocoaArray.writeToFile(filePath, atomically:true);

The second line creates a "Bridged" object of type NSArray, which should give you access to all methods from the foundation.

like image 142
Sergey Kalinichenko Avatar answered Feb 26 '23 20:02

Sergey Kalinichenko