Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NSMutableData to NSData in Swift

I have a method which is returning NSMutableData. I need to pass this NSMutableData to another method but that method is expecting only NSData. I am trying to find any method/solution to convert NSMutableData to NSdata. But still no luck.

In Objective C, it can be done like this NSData *immutableData = [NSData dataWithData:mutableData];

I am not sure how it can be done in Swift?Can someone help me in this?

like image 378
Nitya Avatar asked Oct 14 '16 18:10

Nitya


1 Answers

Simply pass the NSMutableData to any method that expects NSData. Since it's a subclass, it will work fine.

But if you really want to do the conversion, simply do (Swift 3):

let data = someNSMutableDataVariable.copy() as! NSData

or

let data = NSData(data: someNSMutableDataVariable as Data)

It may make sense to update your code to use Data instead of NSMutableData or NSData. Just like using String instead of NSString and NSMutableString.

like image 98
rmaddy Avatar answered Nov 11 '22 02:11

rmaddy