在使用C/C++/OC语言中,经常会用到指针的语法,也理解指针的意义。
在Swift中,将指针包装成不安全的指针类型
。
定义概念对齐
C |
Swift |
const Pointee * |
UnsafePointer<Pointee> |
Pointee * |
UnsafeMutablePointer<Pointee> |
const void * |
UnsafeRawPointer |
void * |
UnsafeMutableRawPointer |
示例
示例一
1 2 3 4 5 6 7 8 9 10 11 12 13
| var age = 10
func test1(_ ptr: UnsafeMutablePointer<Int>){ ptr.pointee += 10 }
func test2(_ ptr: UnsafePointer<Int>) { print(ptr.pointee) }
test1(&age) test2(&age) print(age)
|
示例二
1 2 3 4 5 6 7 8 9 10 11 12 13
| 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) print(age)
|