int to data:
//int to data
var num = -12300
let data = Data.init(bytes: &num, count: MemoryLayout.size(ofValue: num))
// bytes : 8 elements
// - 0 : 244
// - 1 : 207
// - 2 : 255
// - 3 : 255
// - 4 : 255
// - 5 : 255
// - 6 : 255
// - 7 : 255
data to int:
//data to int
let value = data.withUnsafeBytes {
$0.load(as: Int.self)
}
print(value)
// -12300
let value1 = data.withUnsafeBytes { UnsafeRawBufferPointer in
UnsafeRawBufferPointer.load(as: Int.self)
}
print(value1)
// -12300
string to data:
//string to data
let strData = "hello".data(using: .utf8, allowLossyConversion: true)!
// bytes : 5 elements
// - 0 : 104
// - 1 : 101
// - 2 : 108
// - 3 : 108
// - 4 : 111
int to string:
//int to string
let intStr = String(-1234)
print(intStr)
string to int:
//string to int
let strInt = Int(intStr)!
print(strInt)
data to string:
//data to string
let dataStr = String.init(data: strData, encoding: .utf8)!
print(dataStr)
// hello