[swift-evolution] deinit and failable initializers
Charles Srstka
cocoadev at charlessoft.com
Wed Jan 27 10:42:20 CST 2016
On Jan 26, 2016, at 11:15 AM, Chris Eidhof via swift-evolution <swift-evolution at swift.org> wrote:
>
> class MyArray<T> {
> var pointer: UnsafeMutablePointer<T>
> var capacity: Int
>
> init?(capacity: Int) {
> pointer = UnsafeMutablePointer.alloc(capacity)
> if capacity > 100 {
> // Here we should also free the memory. In other words, duplicate the code from deinit.
> return nil
> }
> self.capacity = capacity
>
> }
>
> deinit {
> pointer.destroy(capacity)
> }
> }
In Swift, this sort of pattern is pretty rare. In the cases where you do need to manually allocate memory, you can always wrap the initializer in a “do” block, and release the memory in “catch”.
I don’t think this is a big issue.
Charles
More information about the swift-evolution
mailing list