Last active
March 20, 2025 22:17
-
-
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" π¬π
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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