在c語言中申明一個變量並通過指針修改該變量的值
int a = 1;
int *p = &a;
*p = 2;
printf("a value is %d\\\\n",a);
a value is 2
c語言操作結構體指針操作
申明一個叫User的結構體
typedef struct User{
int ID;
int age;
} User;
申明一個結構體User變量user 設置ID值為1 age值為18
User user;
user.ID = 1;
user.age = 3;
通過指針對變量user的值進行修改
//申明一個結構體指針變量userpointer指向user的地址
User *userpointer = &user;
//修改ID的值為2
int *idPointer = (int *)userpointer;
*idPointer = 2;
//獲得屬性age所在指針
int *agePointer = ++ idPointer;
//修改user的age值為4
*agePointer = 4;
printf("user ID = %d, age = %d", user.ID, user.age);
user ID = 2, age = 4
Swift
Swift並不推薦對指針進行直接操作, 但仍提供了幾種可以直接操作內存的指針類型,以下是c與Swift的語法對應表 ,使用 Type 做類型占用
對於返回值、變量和參數,使用一下對應表
C 語法 Swift 語法
const Type * UnsafePointer
Type * UnsafeMutablePointer
對於類,使用一下語法對應
C 語法 Swift 語法
Type const UnsafePointer
Type __strong UnsafeMutablePointer
Type ** AutoreleasingUnsafeMutablePointer
在Swift中無類型的指針,原始內存可以用UnsafeRawPointer 和UnsafeMutableRawPointer來表示
如果像不完整結構體的這樣的c指針的值的類型無法用Swift來表示,則用OpaquePointer來表示
更多指針相關知識詳見 文檔
接下來,進行Swift版結構體指針操作
申明User結構體
struct User {
var ID: Int
var age: Int
}
申明變量,並獲取變量地址, 創建一個user變量 ID初始值問為1 age初始值為3
通過指針設置ID值為2 設置age值為3
var user = User(ID: 1, age: 3)
let userPointer = withUnsafePointer(to: &user, {$0})//UnsafePointer
//打印user指針的值
print(userPointer.pointee)
//User(ID: 1, age: 3)
//獲取user ID的指針
let userIDPointer = unsafeBitCast(userPointer, to: UnsafeMutablePointer
.self)
//設置ID的值為2
userIDPointer.pointee = 2
print(userPointer.pointee)
//User(ID: 2, age: 3)
//獲取user age的指針
let agePointer = userIDPointer.advanced(by: 1)
agePointer.pointee = 4
print(userPointer.pointee)
//User(ID: 2, age: 4)
雖然c和Swift的語法差距有點大,但是原理是相同的
接下來我們看一個更復雜一點的例子
public struct Person {
var age: Int
var firstName: String
var lastName: String
var phoneNumber: PhoneNumber
}
public struct PhoneNumber {
var number: String
var type: String
}
創建person變量 並通過指針操作 獲取對應的屬性值
let phone = PhoneNumber(number: "186xxxxxxxx", type: "work")
var person = Person(age: 24, firstName: "Bing", lastName: "lin", phoneNumber: phone)
let rawPointer = withUnsafePointer(to: &person, { UnsafeRawPointer($0)})
let age = rawPointer.load(fromByteOffset: 0, as: Int.self)
let firstName = rawPointer.load(fromByteOffset: 8, as: String.self)
let lastName = rawPointer.load(fromByteOffset: 32, as: String.self)
let phoneInfo = rawPointer.load(fromByteOffset: 56, as: PhoneNumber.self)
print("age: \\\\(age) firstName: \\\\(firstName) lastName: \\\\(lastName) , phoneNumber: \\\\(phoneInfo)")
//age: 24 firstName: Bing lastName: lin , phoneNumber: PhoneNumber(number: "186xxxxxxxx", type: "work")
到這裡,我們已經學會了 通過指針獲取值,通過指針設置對應的值
接下來 就可以運用這些知識發揮自己的創造力了