Nitya Nitya - 1 year ago 110
Swift Question

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?

Answer Source

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


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.