我想获取结构的指针,并获取或设置值。代码在这里
protocol TestProtocol {
}
struct TestStruct: TestProtocol {
var username: String?
}
class TestViewModel {
var testStruct: TestProtocol?
func test() -> UnsafeMutablePointer<TestStruct?>? {
guard let _ = self.testStruct as? TestStruct else {
return nil
}
return withUnsafeMutablePointer(to: &(self.testStruct)) { (pointer) -> UnsafeMutablePointer<TestStruct?> in
return pointer.withMemoryRebound(to: TestStruct?.self, capacity: MemoryLayout<TestStruct?>.size) { (point) -> UnsafeMutablePointer<TestStruct?> in
return point
}
}
}
}
func getvalue() {
let testViewModel = TestViewModel()
var testStruct = TestStruct()
testStruct.username = "123"
testViewModel.testStruct = testStruct
print("\(testViewModel.test()?.pointee?.username)")
// here print Optional(""), why not "123"?
}
get value 函数打印结果是错误的,但如果 TestStruct 只有一个 Int 的 var,结果是正确的。就像这样:
struct TestStruct: TestProtocol {
var number: Int?
}
func getvalue() {
let testViewModel = TestViewModel()
var testStruct = TestStruct()
testStruct. number = 123
testViewModel.testStruct = testStruct
print("\(testViewModel.test()?.pointee?.username)")
// Optional(123)
}
为什么?如何解决?