我是Swift的新手,不太明白如何使用UnsafeMutablePointer<T?>
。有人可以帮助我吗?
struct TestStruct {
var a = 0
}
func foo(ptr: UnsafeMutablePointer<TestStruct?>?) {
ptr?.pointee?.a = 123 // pointee is nil, but why?
}
func bar(ptr: TestStruct?) {
print("hello: \(ptr?.a)") // hello: nil
}
var ref = UnsafeMutablePointer<TestStruct?>.allocate(capacity: 1)
foo(ptr: ref)
bar(ptr: ref.pointee)
ref.deallocate(capacity: 1)
我正在为
TestStruct
分配内存,但当我将ref
传递给foo
时,pointee
指向 nil
。如果我使TestStruct
(UnsafeMutablePointer<TestStruct>
) 成为非可选项 - 一切都会很好 - bar打印 hello:123
。
更新:
感谢@MartinR和@Hamish!工作代码:struct TestStruct {
var a = 0
}
func foo(ptr: UnsafeMutablePointer<TestStruct?>?) {
ptr?.pointee?.a = 123
}
func bar(ptr: TestStruct?) {
print("hello: \(ptr?.a)")
}
var ref = UnsafeMutablePointer<TestStruct?>.allocate(capacity: 1)
ref.initialize(to: TestStruct())
foo(ptr: ref)
bar(ptr: ref.pointee)
ref.deinitialize()
ref.deallocate(capacity: 1)
hello: Optional(123)
。 - Martin Rref
的pointee
,因此它可能会保存一些垃圾值,所以当你说pointee?.a = ...
时就无法知道会发生什么。你需要先将pointee
初始化为某个值。 - Hamishhello: Optional(123)
,但是当我在bar(ptr: ref.pointee)
之后添加了print("\(ref.pointee?.a)")
,我又一次收到了一个nil... 这是正常的Playground行为吗? - 0xAT