Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
693 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...