$ 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!") | |
} |