Skip to content

Instantly share code, notes, and snippets.

@moutend
Created March 23, 2021 22:15
Show Gist options
  • Save moutend/d9ef41fafebc71bcd6fe84ac0c1b11c9 to your computer and use it in GitHub Desktop.
Save moutend/d9ef41fafebc71bcd6fe84ac0c1b11c9 to your computer and use it in GitHub Desktop.
[Swift] Save UInt8 array as a file

Save UInt8 array as a file

$ swift write1.swift
$ xxd /path/to/file
00000000: 1234 5678                                .4Vx

The write1.swift is a most easy way. You can also implement your own write() method like the write2.swift.

import Foundation
let a: [UInt8] = [0x12, 0x34, 0x56, 0x78]
let d = Data(a)
do {
try d.write(to: URL(string: "file:///path/to/file")!)
} catch {
print("Oops!")
}
import Foundation
extension Array where Element == UInt8 {
func write(_ path: String) -> Int {
if !FileManager.default.createFile(atPath: path, contents: nil, attributes: nil) {
return -1
}
guard let fh = FileHandle(forWritingAtPath: path) else {
return -2
}
fh.seekToEndOfFile()
fh.write(Data(self))
fh.closeFile()
return self.count
}
}
let a: [UInt8] = [0x12, 0x34, 0x56, 0x78]
if a.write("/path/to/file") < 0 {
print("oops!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment