什么是相当于NSArray的writeToFile:atomically:在Swift和Array? [英] What's the equivalent of NSArray's writeToFile: atomically: in Swift and Array?
问题描述
我一直在学习Swift并构建一个基于Swift的Cocoa应用程序,面对的问题是Swift的内置 Array
类型没有 NSArray
中实现的code> writeToFile:atomically:方法。
那么我该如何将数组的内容写入文件呢? Swift中有什么方法吗? (FYI,我不能找到Swift的数组类型的文档很像 Objective-C的NSArray 。如果是这样,请在评论部分链接。)
不能使用内置的 Array
将数组的内容写入Swift中的文件,什么是最好的替代方法?我认为 NSArray
也可以在Swift代码,但我宁愿避免Objective-C的类。或者应该使用扩展来实现 Array
?
我不知道是否在Swift中存在用于将数组写入文件的原生能力,但是由于数组可以桥接到 NSArray
s,因此您应该能够编写数组到如下的文件:
let mySwiftArray = ... // Swift数组
let cocoaArray:NSArray = mySwiftArray
cocoaArray.writeToFile(filePath,atomically:true);
第二行创建一个类型为 NSArray
,它应该允许你访问基金会的所有方法。
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.
这篇关于什么是相当于NSArray的writeToFile:atomically:在Swift和Array?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!