有時上傳或者發送圖片、文字時,需要將數據轉換為 bytes 字節數組。下面介紹兩種將 Data 轉換為 [UInt8] 的方法。
假設我們有如下
Data 數據要轉換:
1
|
let
data =
"航歌"
.data(using: .utf8)!
|
方法一:使用 [UInt8] 新的構造函數
1
2
|
let
bytes = [
UInt8
](data)
print
(bytes)
|
方法二:通過 Pointer 指針獲取
1
2
3
4
|
let
bytes = data.withUnsafeBytes {
[
UInt8
](
UnsafeBufferPointer
(start: $0, count: data.count))
}
print
(bytes)
|