I have a code that has same data in two forms Tuple and Struct, they are both tested by converting to the same Final Struct, however the code only compiles for the struct whereas fails for the tuple, is there something fundamentally different with tuples that prevents using them with ownership?
typealias TupleIntPoint = (
x: Int,
y: Int,
)
struct StructIntPoint {
var x: Int
var y: Int
}
// Final struct to convert to
struct StructFloatPoint {
var x: Float
var y: Float
}
/// * This function compiles ok
func testBorrowingStruct(
_ ip: borrowing StructIntPoint,
) -> StructFloatPoint {
let p: StructFloatPoint = convertStruct(ip)
return p
}
/// * This function does not compile
/// * ERROR: 'iPoint' is borrowed and cannot be consumed
/// * even though all functions are borrowing
func testBorrowingTuple(
_ ip: borrowing TupleIntPoint,
) -> StructFloatPoint {
let p: StructFloatPoint = convertTuple(ip)
return p
}
func convertStruct(_ ip: borrowing StructIntPoint) -> StructFloatPoint {
return StructFloatPoint(x: Float(ip.x), y: Float(ip.y))
}
func convertTuple(_ ip: borrowing TupleIntPoint) -> StructFloatPoint {
return StructFloatPoint(x: Float(ip.x), y: Float(ip.y))
}
It should be possible for a tuple to contain noncopyable elements, rendering the tuple noncopyable if any of its elements are. Since tuples' structure is always known, it would be reasonable to allow for the elements within a tuple to be independently borrowed, mutated, and consumed, as the language allows today for the elements of a tuple to be independently mutated via inout accesses. (Due to the limitations of dynamic exclusivity checking, this would not be possible for class properties, globals, and escaping closure captures.)
not sure what the current state of the world is for potentially supporting that behavior though – as you've shown, things do not yet work as described in that section.
to be clear, i'm no authority on these questions, just an interested party. opening an issue seems entirely reasonable to me – perhaps a feature request vs a bug report given the fact that it appears to be a known limitation cited in the linked evolution document. it seems there is already at least one report that appears along the same lines: Borrowed Tuple Elements Cause Consumption Error · Issue #74346 · swiftlang/swift · GitHub