How to convert an Int into NSData in Swift?

前端 未结 7 1922
陌清茗
陌清茗 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:41

    For any integer type:

    extension FixedWidthInteger {
        var data: Data {
            let data = withUnsafeBytes(of: self) { Data($0) }
            return data
        }
    }
    

    Example:

    let data = 1.data
    

提交回复
热议问题