objective-cswiftnsmutabledata

Why would an empty NSMutableData be optional?


I'm converting a project from Objective-C to Swift. In it, there is a NSMutableData object that was originally instantiated like this:

NSMutableData *buffer = [[NSMutableData alloc] initWithLength:65535];

In Swift, when I try to instantiate it the same way, it produces an optional (and the function I'm using it in doesn't work with an optional, so it gets a bit messy if I do it this way unless I can be sure it's safe to force unwrap it):

let buffer = NSMutableData(length: 65535) // optional

But I can do what appears to be the exact same thing in two steps and get a non-optional:

let buffer = NSMutableData() // not optional
buffer.length = 65535

As far as I can tell, I get the same result either way, so why is only the first one optional? Is there any reason it wouldn't be safe to force unwrap it, or any disadvantage to doing it the second way?


Solution

  • I guess that init(length:) is the safe way of trying to allocate a certain number of bytes, that may safely fail and return nil. But if you change the length property of your mutable data object and malloc fails, then an exception is thrown.

    If I needed to allocate a huge number of bytes and I was not sure if malloc will succeed, then I'd use a guard statement:

    guard let buffer = NSMutableData(length: N) else { return }