Created
May 28, 2020 09:50
-
-
Save d4rkd3v1l/96617585d62b0872ef0ebb7b2e7a8ba2 to your computer and use it in GitHub Desktop.
Swift @propertyWrapper 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