无法将不可变值作为 inout 参数传递:'pointee' 是一个 get-only 属性
Cannot pass immutable value as inout argument: 'pointee' is a get-only property
来自 the Apple Docs 的这段代码给我:
Cannot pass immutable value as inout argument: 'pointee' is a get-only property
import Foundation
import Darwin
extension sockaddr_storage {
//...
static func fromSockAddr<AddrType, ReturnType>(_ body: (_ sax: inout AddrType) throws -> ReturnType) rethrows -> (ReturnType, sockaddr_storage) {
precondition(MemoryLayout<AddrType>.size <= MemoryLayout<sockaddr_storage>.size)
// We need a mutable `sockaddr_storage` so that we can pass it to `withUnsafePointer(to:_:)`.
var ss = sockaddr_storage()
let result = try withUnsafePointer(to: &ss) {
try [=12=].withMemoryRebound(to: AddrType.self, capacity: 1) {
// Error: Cannot pass immutable value as inout argument: 'pointee' is a get-only property
try body(&[=12=].pointee)
}
}
return (result, ss)
}
}
我找不到编译它的方法。
您只需要将 withUnsafePointer
更改为 withUnsafeMutablePointer
。
之所以可行,是因为 withMemoryRebound
现在传入 UnsafeMutablePointer<T>
而不是 UnsafePointer<T>
,因此您可以改变 pointee
.
代码:
extension sockaddr_storage {
//...
static func fromSockAddr<AddrType, ReturnType>(_ body: (_ sax: inout AddrType) throws -> ReturnType) rethrows -> (ReturnType, sockaddr_storage) {
precondition(MemoryLayout<AddrType>.size <= MemoryLayout<sockaddr_storage>.size)
var ss = sockaddr_storage()
let result = try withUnsafeMutablePointer(to: &ss) {
try [=10=].withMemoryRebound(to: AddrType.self, capacity: 1) {
try body(&[=10=].pointee)
}
}
return (result, ss)
}
}
来自 the Apple Docs 的这段代码给我:
Cannot pass immutable value as inout argument: 'pointee' is a get-only property
import Foundation
import Darwin
extension sockaddr_storage {
//...
static func fromSockAddr<AddrType, ReturnType>(_ body: (_ sax: inout AddrType) throws -> ReturnType) rethrows -> (ReturnType, sockaddr_storage) {
precondition(MemoryLayout<AddrType>.size <= MemoryLayout<sockaddr_storage>.size)
// We need a mutable `sockaddr_storage` so that we can pass it to `withUnsafePointer(to:_:)`.
var ss = sockaddr_storage()
let result = try withUnsafePointer(to: &ss) {
try [=12=].withMemoryRebound(to: AddrType.self, capacity: 1) {
// Error: Cannot pass immutable value as inout argument: 'pointee' is a get-only property
try body(&[=12=].pointee)
}
}
return (result, ss)
}
}
我找不到编译它的方法。
您只需要将 withUnsafePointer
更改为 withUnsafeMutablePointer
。
之所以可行,是因为 withMemoryRebound
现在传入 UnsafeMutablePointer<T>
而不是 UnsafePointer<T>
,因此您可以改变 pointee
.
代码:
extension sockaddr_storage {
//...
static func fromSockAddr<AddrType, ReturnType>(_ body: (_ sax: inout AddrType) throws -> ReturnType) rethrows -> (ReturnType, sockaddr_storage) {
precondition(MemoryLayout<AddrType>.size <= MemoryLayout<sockaddr_storage>.size)
var ss = sockaddr_storage()
let result = try withUnsafeMutablePointer(to: &ss) {
try [=10=].withMemoryRebound(to: AddrType.self, capacity: 1) {
try body(&[=10=].pointee)
}
}
return (result, ss)
}
}