構造体のポインタを取得し、値を取得または設定したい。コードはこちら
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 の変数しかない場合、結果は正しいです。そのように:
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)
}
なぜ?それを修正する方法は?