Ces*_*are 20 int nsdata ios swift
在Objective-C中,我使用以下代码
将Int变量转换NSData为字节数据包.
int myScore = 0;
NSData *packet = [NSData dataWithBytes:&myScore length:sizeof(myScore)];
Run Code Online (Sandbox Code Playgroud)将转换后的NSData变量用于方法.
[match sendDataToAllPlayers:
packet withDataMode: GKMatchSendDataUnreliable
error: &error];
Run Code Online (Sandbox Code Playgroud)我尝试将Objective-C代码转换为Swift:
var myScore : Int = 0
func sendDataToAllPlayers(packet: Int!,
withDataMode mode: GKMatchSendDataMode,
error: NSErrorPointer) -> Bool {
return true
}
Run Code Online (Sandbox Code Playgroud)
但是,我无法将Int变量转换为a NSData并将其用作方法.我怎样才能做到这一点?
Rap*_*ael 45
使用Swift 3.x和4.0:
var myInt = 77
var myIntData = Data(bytes: &myInt,
count: MemoryLayout.size(ofValue: myInt))
Run Code Online (Sandbox Code Playgroud)
Rob*_*Rob 27
要转换Data为Int:
let score = 1000
let data = withUnsafeBytes(of: score) { Data($0) }
Run Code Online (Sandbox Code Playgroud)
要将其转换回来:
e8 03 00 00 00 00 00 00
Run Code Online (Sandbox Code Playgroud)
对于任何整数类型:
extension FixedWidthInteger {
var data: Data {
let data = withUnsafeBytes(of: self) { Data($0) }
return data
}
}
Run Code Online (Sandbox Code Playgroud)
例子:
let data = 1.data
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23434 次 |
| 最近记录: |