Swift: 为什么 init?(length length: Int) NSMutableData 的初始化程序会失败?
Swift: Why is the init?(length length: Int) NSMutableData's initializer failable?
内存分配可能会失败,但我认为 Swift 无法处理这种情况。
github 上的代码调用了一个不可失败的初始化器
public convenience init?(length: Int) {
let memory = malloc(length)
self.init(bytes: memory, length: length, copy: false) { buffer, amount in
free(buffer)
}
}
编辑:
代码来自 Swift 3.
中的 native-Swift Foundation 框架
来自 swift- 用户列表:
"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."-克里斯
内存分配可能会失败,但我认为 Swift 无法处理这种情况。 github 上的代码调用了一个不可失败的初始化器
public convenience init?(length: Int) {
let memory = malloc(length)
self.init(bytes: memory, length: length, copy: false) { buffer, amount in
free(buffer)
}
}
编辑: 代码来自 Swift 3.
中的 native-Swift Foundation 框架来自 swift- 用户列表:
"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."-克里斯