How to convert an Int into NSData in Swift?

前端 未结 7 1910
陌清茗
陌清茗 2021-02-03 22:37

In Objective-C I use the following code to

  1. Convert an Int variable into NSData, a packet of bytes.

    int myScore = 0;
    NS         
    
    
            
7条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-03 22:47

    Depending on the size of Int you are working with, a straight forward approach is to init Data with Sequence of UInt8:

    let value: Int = 100
    let data = Data([UInt8(value)])
    // OR
    let data = Data([0xFF, 0xFE])
    

提交回复
热议问题