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 wri
This will work...
let array = ["One", "Two", "Three"] as NSArray
array.writeToFile("/Users/xxx/Desktop/trial.txt", atomically:true)
Output is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<string>One</string>
<string>Two</string>
<string>Three</string>
</array>
</plist>
But you must cast it as an NSArray
let array = ["One", "Two", "Three"] // Native Swift array will not work
array.writeToFile("/Users/xxx/Desktop/trial.txt", atomically:true)
will not work.
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.