Skip to content

What is the difference between data and NSData in Swift?

NSData

swift
class NSData : NSObject
class NSData : NSObject

NSData and its mutable subclass NSMutableData provide data objects, or object-oriented wrappers for byte buffers.

NSData is toll-free bridged with its Core Foundation counterpart, CFData.

Data

swift
@frozen
struct Data
@frozen
struct Data

The Data value type allows simple byte buffers to take on the behavior of Foundation objects.

Data bridges to the NSData class and its mutable subclass, NSMutableData. You can use these interchangeably in code that interacts with Objective-C APIs.

Convert Between Data and NSData using as

swift
if let nsdata = NSData(contentsOf: URL(string: "https://seacode.uk")!) {
    print(nsdata.length)
    let data:Data = nsdata as Data
    print(data.count)
}

do {
    let data = try Data(contentsOf: URL(string: "https://seacode.uk")!)
    print(data.count)
    let nsdata:NSData = data as NSData
    print(nsdata.length)
}catch{
    print(error)
}
if let nsdata = NSData(contentsOf: URL(string: "https://seacode.uk")!) {
    print(nsdata.length)
    let data:Data = nsdata as Data
    print(data.count)
}

do {
    let data = try Data(contentsOf: URL(string: "https://seacode.uk")!)
    print(data.count)
    let nsdata:NSData = data as NSData
    print(nsdata.length)
}catch{
    print(error)
}

References