Search code examples
swiftswift2nsdatainitializerfailable

Swift: Why is the init?(length length: Int) NSMutableData's initializer failable?


The memory allocation can fail, but I think Swift doesn't handle that cases. The code on github calls a non failable initializer

public convenience init?(length: Int) {
    let memory = malloc(length)
    self.init(bytes: memory, length: length, copy: false) { buffer, amount in
        free(buffer)
    }
}

EDIT: The code is from the native-Swift Foundation framework coming in Swift 3.


Solution

  • From the swift-users list:

    "Swift’s policy on memory allocation failure is that fixed-size object allocation is considered to be a runtime failure if it cannot be handled. OTOH, APIs that can take a variable and arbitrarily large amount to allocate should be failable. NSData falls into the later category." -Chris