Meysam Hasanloo
Meysam Hasanloo

Reputation: 183

How to append two NSData variable in swift?

I want to append two NSData:

    var actionIdData :NSData = NSData(bytes: &actionId, length: 2)
    var payLoad : NSData = NSData(bytes: &message, length: 9)

    var messageData : NSMutableData!

    messageData.appendData(actionIdData)
    messageData.appendData(actionIdData)

fatal error: unexpectedly found nil while unwrapping an Optional value

Upvotes: 14

Views: 11420

Answers (3)

Sentry.co
Sentry.co

Reputation: 5569

Convenient extension for Swift 5

extension Array where Element == Data {
   /**
    * Combines data
    * ## Examples:
    * [Data(),Data()].combined
    */
   var combined: Data {
      reduce(.init(), +)
   }
}

Upvotes: 0

abdullahselek
abdullahselek

Reputation: 8435

Compatible with both Swift 4 and Swift 5 you can only use append function of Data to append two different data.

Sample Usage

guard var data1 = "data1".data(using: .utf8), let data2 = "data2".data(using: .utf8) else {
    return
}

data1.append(data2)
// data1 is now combination of data1 and data2

Upvotes: 4

Nirav D
Nirav D

Reputation: 72410

You need to initialize your messageData before appending to it.

var messageData = NSMutableData() //or var messageData : NSMutableData = NSMutableData()
messageData.appendData(actionIdData)
messageData.appendData(payLoad)

Upvotes: 15

Related Questions