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
?
I am not sure if the "native" ability for writing arrays to files exists in Swift, but since arrays can be bridged to NSArray
s, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With