如何使用Swift将Data/NSData转换为整数数组

Mys*_*oid 1 arrays ios swift swift3

我有一个数据,我从服务中的一个特征收到

let value = characteristic.value
Run Code Online (Sandbox Code Playgroud)

数据类型的这个"值".

在此值中,有20个字节包含5个类型为Uint8或int 1,2,3,4,5的数字.

如何从此数据值中获取这些整数?

ERb*_*tuu 5

1)如果你有stingyfy josn(来自API响应),那么你可以转换为直接[Int]使用..

do {
    let IntArray = try JSONSerialization.jsonObject(with: dataObject, options:[])
    print(IntArray)
    // print: 1,2,3,4,5,6,7,8,9
}catch{
    print("Error in Serialization")
}
Run Code Online (Sandbox Code Playgroud)

2)如果你想[Int] and Data转换,那么使用它

您可以使用'archivedData' 创建Data[Int]使用返回'[Int]' unarchiveObject.

var listOfInt : [Int] = [1,2,3,4,5,6,7,8,9]

let dataObject = NSKeyedArchiver.archivedData(withRootObject: listOfInt)

if let objects = NSKeyedUnarchiver.unarchiveObject(with: dataObject) as? [Int] {
    print(objects)
    // print: 1,2,3,4,5,6,7,8,9
} else {
    print("Error while unarchiveObject")
}
Run Code Online (Sandbox Code Playgroud)