NSData to [Uint8] in Swift

后端 未结 7 728
无人及你
无人及你 2020-12-04 17:24

I couldn\'t find a solution to this problem in Swift (all of them are Objective-C, and they deal with pointers which I don\'t think exist in Swift in the same form). Is ther

相关标签:
7条回答
  • 2020-12-04 18:05

    It's funny but exist more simple solution. Works in Swift 3. Surely. I've used this today.

    data: Data // as function parameter    
    let byteArray = [UInt8](data)
    

    That's all! :) NSData easily bridged to Data.

    UPDATE: (due to Andrew Koster comment)

    Swift 4.1, Xcode 9.3.1

    Just has been rechecked - all works as expected.

    if let nsData = NSData(base64Encoded: "VGVzdFN0cmluZw==", options: .ignoreUnknownCharacters) {
    let bytes = [UInt8](nsData as Data)
    print(bytes, String(bytes: bytes, encoding: .utf8))
    

    Output: [84, 101, 115, 116, 83, 116, 114, 105, 110, 103] Optional("TestString")

    0 讨论(0)
提交回复
热议问题