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

前端 未结 2 1719
再見小時候
再見小時候 2020-12-19 16:32

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

相关标签:
2条回答
  • 2020-12-19 16:59

    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.

    0 讨论(0)
  • 2020-12-19 17:14

    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.

    0 讨论(0)
提交回复
热议问题