What is your evaluation of the proposal?
+1 to adding the ability to access the offset. But I do have some questions about the specific design choices.
Maybe I'm missing something obvious, but the example in the proposal doesn't seem to match the declaration:
extension MemoryLayout {
func offset(of key: PartialKeyPath<T>) -> Int?
}
This declaration returns Int?
rather than Int
. This is necessary due to the choice to use a function which accepts an arbitrary PartialKeyPath<T>
. However, the example doesn't appear to handle the optional result:
var root: T, value: U
var key: WritableKeyPath<T, U>
// Mutation through the key path...
root[keyPath: \.key] = value
// ...is exactly equivalent to mutation through the offset pointer...
withUnsafePointer(to: &root) {
(UnsafeMutableRawPointer($0) + MemoryLayout<T>.offset(of: \.key))
// ...which can be assumed to be bound to the target type
.assumingMemoryBound(to: U.self).pointee = value
}
Let's rewrite the example to handle the optional:
withUnsafePointer(to: &root) {
guard let offset = MemoryLayout<T>.offset(of: \.key) else {
/// what do we do here???
return
}
(UnsafeMutableRawPointer($0) + offset)
// ...which can be assumed to be bound to the target type
.assumingMemoryBound(to: U.self).pointee = value
}
I am wondering if a design that was focused on providing offsets for properties that can be statically verified to be directly addressable is viable (and therefore return Int
rather than Int?
, producing a compiler error if the specified property is not directly addressable). If it is, should that be offered in place of or along side the dynamic version? If a design along these lines isn't viable, what specific challenges are there?
Is the problem being addressed significant enough to warrant a change to Swift?
Yes, definitely.
Does this proposal fit well with the feel and direction of Swift?
In general, yes. But see the questions listed above.
If you have used other languages or libraries with a similar feature, how do you feel that this proposal compares to those?
I have used C. From a programmer's point of view, the most significant difference is that offsets in C are not optional. Swift is a higher level language that cannot provide an offset for every property, but perhaps it would be better to statically verify the direct addressability of a property when possible to avoid the need to manually handle nil in all code that works with offsets.
How much effort did you put into your review? A glance, a quick reading, or an in-depth study?
A quick, but detailed reading.