在使用C/C++/OC语言中,经常会用到指针的语法,也理解指针的意义。
在Swift中,将指针包装成**不安全**的指针类型。
| C | Swift |
|---|---|
const Pointee * |
UnsafePointer<Pointee> |
Pointee * |
UnsafeMutablePointer<Pointee> |
const void * |
UnsafeRawPointer |
void * |
UnsafeMutableRawPointer |
var age = 10
func test1(_ ptr: UnsafeMutablePointer<Int>){
ptr.pointee += 10
}
func test2(_ ptr: UnsafePointer<Int>) {
print(ptr.pointee)
}
test1(&age)
test2(&age) // 20
print(age) // 20
var age = 10
func test3(_ ptr: UnsafeMutableRawPointer) {
ptr.storeBytes (of: 20, as: Int.self)
}
func test4(_ ptr: UnsafeRawPointer) {
print(ptr.load(as: Int.self))
}
test3(&age)
test4(&age) // 20
print(age) // 20