Swift 无法理解withUnsafeBytes方法如何工作

Swift 无法理解withUnsafeBytes方法如何工作,swift,unsafe-pointers,Swift,Unsafe Pointers,我正在尝试将数据转换为非安全指针。我找到了一个答案,我可以使用withUnsafeBytes来获取字节 然后我自己做了一个小测试,看看是否可以打印出字符串“abc”的字节值 那么,我怎样才能得到这三个字符的字节值呢?指针指向序列中第一个字节的地址。如果想要指向其他字节的指针,则必须使用指针算法,即将指针移动到下一个地址: testData.withUnsafeBytes{ (bytes: UnsafePointer<UInt8>) -> Void in NSLog("\

我正在尝试将数据转换为非安全指针。我找到了一个答案,我可以使用withUnsafeBytes来获取字节

然后我自己做了一个小测试,看看是否可以打印出字符串“abc”的字节值

那么,我怎样才能得到这三个字符的字节值呢?

指针指向序列中第一个字节的地址。如果想要指向其他字节的指针,则必须使用指针算法,即将指针移动到下一个地址:

testData.withUnsafeBytes{ (bytes: UnsafePointer<UInt8>) -> Void in
    NSLog("\(bytes.pointee)")
    NSLog("\(bytes.successor().pointee)")
    NSLog("\(bytes.advanced(by: 2).pointee)")
}
testData.withUnsafeBytes{(字节:UnsafePointer)->Void in
NSLog(“\(bytes.pointee)”)
NSLog(“\(bytes.succession().pointee)”)
NSLog(\(bytes.advanced(by:2.pointee)”)
}

testData.withUnsafeBytes{(字节:UnsafePointer)->中的Void
NSLog(“\(字节[0])”)
NSLog(“\(字节[1])”)
NSLog(“\(字节[2])”)
}
但是,您必须知道testData的字节大小,并且不要使其溢出。

指针指向序列中第一个字节的地址。如果想要指向其他字节的指针,则必须使用指针算法,即将指针移动到下一个地址:

testData.withUnsafeBytes{ (bytes: UnsafePointer<UInt8>) -> Void in
    NSLog("\(bytes.pointee)")
    NSLog("\(bytes.successor().pointee)")
    NSLog("\(bytes.advanced(by: 2).pointee)")
}
testData.withUnsafeBytes{(字节:UnsafePointer)->Void in
NSLog(“\(bytes.pointee)”)
NSLog(“\(bytes.succession().pointee)”)
NSLog(\(bytes.advanced(by:2.pointee)”)
}

testData.withUnsafeBytes{(字节:UnsafePointer)->中的Void
NSLog(“\(字节[0])”)
NSLog(“\(字节[1])”)
NSLog(“\(字节[2])”)
}

但是,您必须知道testData的字节大小,并且不要使其溢出。

您得到的是'97',因为'bytes'指向'testData'的起始地址

您可以获得所有三个或n个字符的字节值,如以下代码所示:

let testData: Data = "abc".data(using: String.Encoding.utf8)!
print(testData.count)
testData.withUnsafeBytes(
    {(bytes: UnsafePointer<UInt8>) -> Void in
        for idx in 0..<testData.count {
            NSLog("\(bytes[idx])")
        }
})
让testData:Data=“abc”.Data(使用:String.Encoding.utf8)!
打印(testData.count)
testData.withUnsafeBytes(
{(字节:UnsafePointer)->中的Void

对于0..中的idx,您得到的是'97',因为'bytes'指向'testdata'的起始地址

您可以获得所有三个或n个字符的字节值,如以下代码所示:

let testData: Data = "abc".data(using: String.Encoding.utf8)!
print(testData.count)
testData.withUnsafeBytes(
    {(bytes: UnsafePointer<UInt8>) -> Void in
        for idx in 0..<testData.count {
            NSLog("\(bytes[idx])")
        }
})
让testData:Data=“abc”.Data(使用:String.Encoding.utf8)!
打印(testData.count)
testData.withUnsafeBytes(
{(字节:UnsafePointer)->中的Void

对于0中的idx..@MartinR-Oh-yes,忘记了明显的内容。@MartinR-Oh-yes,忘记了明显的内容。请注意,您可以打印所有字节,而无需使用
withUnsafeBytes:
Just
for testData中的字节{print(byte)}
@MartinR不知道这一点。谢谢!请注意,您可以打印所有字节,而无需使用
with unsafebytes:
只需
用于testData中的字节{print(byte)}
@MartinR不知道这一点。谢谢!
let testData: Data = "abc".data(using: String.Encoding.utf8)!
print(testData.count)
testData.withUnsafeBytes(
    {(bytes: UnsafePointer<UInt8>) -> Void in
        for idx in 0..<testData.count {
            NSLog("\(bytes[idx])")
        }
})