Skip to content

Instantly share code, notes, and snippets.

@d4rkd3v1l
Last active September 13, 2022 06:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d4rkd3v1l/ab582a7cafd3a8b8c164c8541a3eef96 to your computer and use it in GitHub Desktop.
Save d4rkd3v1l/ab582a7cafd3a8b8c164c8541a3eef96 to your computer and use it in GitHub Desktop.
Swift @propertyWrappers to allocate huge structs on the heap, by wrapping them inside arrays. -> Very effective "hackaround" 😬😎
/// Stores value types on the heap
///
/// Arrays are stored on the heap and only the pointer (8 bytes) to the array remains on the stack.
/// This behaviour is used to wrap another type into an array, and therefore move it to the heap.
///
/// Example usage:
/// ```
/// @StoredOnHeap var hugeStruct: HugeStruct
/// ```
@propertyWrapper
struct StoredOnHeap<T> {
private var value: [T]
init(wrappedValue: T) {
self.value = [wrappedValue]
}
var wrappedValue: T {
get {
return self.value[0]
}
set {
self.value[0] = newValue
}
}
}
/// Stores optional value types on the heap
///
/// Arrays are stored on the heap and only the pointer (8 bytes) to the array remains on the stack.
/// This behaviour is used to wrap another type into an array, and therefore move it to the heap.
///
/// Example usage:
/// ```
/// @StoredOnHeap var hugeStruct: HugeStruct?
/// ```
@propertyWrapper
struct StoredOnHeapOptional<T> {
private var value: [T] = []
init() {}
init(wrappedValue: T?) {
if let wrappedValue = wrappedValue {
self.value = [wrappedValue]
}
}
var wrappedValue: T? {
get {
return self.value.first
}
set {
self.value = []
if let newValue = newValue {
self.value.append(newValue)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment