NSData from UInt8

前端 未结 3 1239
心在旅途
心在旅途 2020-12-18 23:40

I have recently found a source code in swift and I am trying to get it to objective-C. The one thing I was unable to understand is this:

var theData:UInt8!

         


        
相关标签:
3条回答
  • 2020-12-19 00:17

    In Swift,

    Data has a native init method.

    // Foundation -> Data  
    
    /// Creates a new instance of a collection containing the elements of a
    /// sequence.
    ///
    /// - Parameter elements: The sequence of elements for the new collection.
    ///   `elements` must be finite.
    @inlinable public init<S>(_ elements: S) where S : Sequence, S.Element == UInt8
    
    @available(swift 4.2)
    @available(swift, deprecated: 5, message: "use `init(_:)` instead")
    public init<S>(bytes elements: S) where S : Sequence, S.Element == UInt8
    

    So, the following will work.

    let values: [UInt8] = [1, 2, 3, 4]
    let data = Data(values)
    
    0 讨论(0)
  • 2020-12-19 00:23

    In Swift 3

    var myValue: UInt8 = 3 // This can't be let properties
    let value = Data(bytes: &myValue, count: MemoryLayout<UInt8>.size)
    
    0 讨论(0)
  • 2020-12-19 00:27

    If you write the Swift code slightly simpler as

    var theData : UInt8 = 3
    let data = NSData(bytes: &theData, length: 1)
    

    then it is relatively straight-forward to translate that to Objective-C:

    uint8_t theData = 3;
    NSData *data = [NSData dataWithBytes:&theData length:1];
    

    For multiple bytes you would use an array

    var theData : [UInt8] = [ 3, 4, 5 ]
    let data = NSData(bytes: &theData, length: theData.count)
    

    which translates to Objective-C as

    uint8_t theData[] = { 3, 4, 5 };
    NSData *data = [NSData dataWithBytes:&theData length:sizeof(theData)];
    

    (and you can omit the address-of operator in the last statement, see for example How come an array's address is equal to its value in C?).

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