Skip to content

Instantly share code, notes, and snippets.

@beccadax
Created December 7, 2019 06:45
Show Gist options
  • Save beccadax/78a092ad4e86b38e8073d3585530bbae to your computer and use it in GitHub Desktop.
Save beccadax/78a092ad4e86b38e8073d3585530bbae to your computer and use it in GitHub Desktop.
/// Passes a pointer to an uninitialized instance of `type` to `body`.
/// If `body` returns `true`, indicating that the memory has now been
/// initialized, returns the instance; otherwise returns `nil`.
@usableFromInline func withUninitialized<T>(
_ type: T.Type, do body: (UnsafeMutablePointer<T>) -> Bool
) -> T? {
let ptr = UnsafeMutablePointer<T>.allocate(capacity: 1)
defer { ptr.deallocate() }
guard body(ptr) else {
return nil
}
return ptr.move()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment