[swift-users] NSMutableData's init?(length length: Int) initializer

Jacob Bandes-Storch jtbandes at gmail.com
Thu Apr 14 17:18:53 CDT 2016


It's easy to test this in a playground on OS X:

    NSMutableData(length: 1000000000000000)   // returns nil

It makes sense that the swift-corelibs-foundation version of NSMutableData
should work the same way.
Jacob

On Thu, Apr 14, 2016 at 11:56 AM, Jens Alfke via swift-users <
swift-users at swift.org> wrote:

>
> On Apr 14, 2016, at 10:45 AM, soyer via swift-users <swift-users at swift.org>
> wrote:
>
> Do you know why is the init?(length length: Int) NSMutableData's
> initializer failable?
>
>
> Because the Objective-C declaration in <Foundation/NSData.h> declares the
> return type as ‘nullable’:
>
> - (nullable instancetype)initWithLength:(NSUInteger)length;
>
> The memory allocation can fail, but I think Swift doesn't handle that
> cases. (it is not a real issue in a modern OS)
>
>
> Not on a modern 64-bit desktop OS, but it can be an issue on some other
> platforms. In a 32-bit process (still supported on iOS and Mac OS) malloc
> can fail if the process's address space is fragmented enough that there are
> no free blocks large enough for the allocation. On an OS without a VM
> pager, like many embedded systems, malloc can fail if physical RAM is
> exhausted.
>
> (I’m actually not sure if this is the reason why that initializer is
> failable. It’s possible this is a mistake, or Apple’s frameworks team had
> some other architectural reason for allowing it to fail. Historically, the
> design pattern for initializers in Objective-C always allows them to return
> nil.)
>
> The code on github calls a non failable initializer.
>
>
> That’s for the native-Swift Foundation framework coming in Swift 3. I’d
> guess they’ve adopted the same method signature as in Apple’s Foundation,
> for compatibility.
>
> —Jens
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160414/4dbd8ea2/attachment.html>


More information about the swift-users mailing list