I want to get a value of Int32
through an Int32 Pointer
.
var result:Int32 = 32
var y = withUnsafePointer(&result, {(point:UnsafePointer<Int32>) -> UnsafePointer<Int32> in
return point
})
It is like every UnsafePointer<>. Example: NSErrorPointer
which is an AutoreleasingUnsafePointer<NSError?>
you can get the value with the memory attribute.
Use the attribute memory
var errPtr: UnsafePointer<NSError> = ...
var err: NSError = errPtr.memory // not optional
Solution to your example is very easy then:
var result:Int32 = 32
var y = withUnsafePointer(&result, {(point:UnsafePointer<Int32>) -> UnsafePointer<Int32> in
return point
})
y.memory // in the playground it shows 32 :-D
There is no dereference operator in Swift, in C it was the aterisk *
, but that is not possible in Swift.
The documentation is very helpful.
The type UnsafePointer<Memory>
has a subscript operator. Provided that the pointer points to something, subscript 0 always exists, so this works in a playground and it has the advantage that the reference guide has the subscript documented but not the memory
property.
var result:Int32 = 32
var y = withUnsafePointer(&result, {(point:UnsafePointer<Int32>) -> UnsafePointer<Int32> in
return point
})
y[0] // 32
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.