Hi everyone. While experimenting with creating a simple Box type in Swift (6.3.3), I've ran into some issues and I'm wondering if you guys could enlighten me. In practice I would use indirect.
The code:
do {
struct Box<T: ~Copyable>: ~Copyable {
private let p = UnsafeMutablePointer<T>.allocate(capacity: 1)
/*
var pointee: T {
borrowing get { p.pointee }
// Error: 'self.p.pointee' is borrowed and cannot be consumed
}
*/
func with(_ f: (borrowing T) -> ()) {
f(p.pointee)
}
init (_ v: consuming T) {
p.initialize(to: v)
}
deinit {
p.deallocate()
}
}
struct A: ~Copyable { let a: Int }
struct Foo: ~Copyable {
let a: A
let b: A
}
enum Node: ~Copyable {
case cons(Int, Box<Node>)
case empty
}
let l = Node.cons(5, Box(Node.cons(4, Box(Node.empty))))
if case let .cons(_, b) = l {
/*
b.with { p in
// error: 'p' is borrowed and cannot be consumed
if case .cons(let i, _) = p {
print(i)
}
}
*/
b.with { p in
switch p {
case .cons(let i, _): print(i)
default: break
}
}
}
}
-
Why does
borrowing get { p.pointee }cause an error, butfunc with(_ f: (borrowing T) -> ())work? Are they not doing similar things? -
Why does the
if casefail while theswitchworks?