Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
689 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...