Created
November 4, 2019 04:02
-
-
Save fmo91/abe7f69f3c106f54ed87fc28e5c85701 to your computer and use it in GitHub Desktop.
This file contains 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
// @propertyWrapper annotation makes this | |
// struct a property wrapper. | |
// It will be a generic struct because we will make | |
// it work with any kind of value type. | |
@propertyWrapper | |
struct Sorted<T> { | |
// Internally, we will store the actual value of | |
// the array in this property | |
private var value: [T] | |
// As we want to sort the array each time we introduce a new | |
// value in it, we need to store the sort function. | |
private let sortFunction: (T, T) -> Bool | |
// The only requisite for a struct to be a propertyWrapper is this | |
// computed property. | |
// The wrappedValue property is accesible from the outside. | |
// Each time we want to get the property value, the getter will | |
// be called, and each time we want to set a value for this | |
// property, its setter will be called. | |
var wrappedValue: [T] { | |
get { return value } | |
set { value = newValue.sorted(by: sortFunction) } | |
} | |
// In the init, we have the special argument `wrappedValue`, | |
// that represents the initial assigned value | |
// and we will also send a sortFunction that will be used for | |
// sorting the array each time we add a new value to it. | |
init(wrappedValue value: [T], by sortFunction: @escaping (T, T) -> Bool) { | |
self.sortFunction = sortFunction | |
self.value = value.sorted(by: sortFunction) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment