Swift 3必看:sizeof移進MemoryLayout

在學習Swift 3的過程當中整理了一些筆記,若是想看其餘相關文章可前往《Swift 3必看》系列目錄git

sizeof這個方法名直接取自C語言,可是實際上LLVM中並無一個函數叫sizeof。並且sizeof的使用範圍很窄,不像mapfilter這種常常會全局用到。因此從新定義了一個結構體 MemoryLayout 來實現原來sizeof的功能,使用上也有變化。github

主要有兩種方式,一種是直接經過泛型參數從靜態變量獲取:swift

let stringSize = MemoryLayout<String>.size複製代碼

也能夠經過調用靜態方法獲取app

let stringValue = "A"
let varSize = MemoryLayout.size(ofValue: stringValue)複製代碼

二者都會獲得正確的結果:ide

除了sizeof, MemoryLayout還能夠獲取stride alignment 函數

歡迎關注個人微博:@沒故事的卓同窗學習

相關連接: SE-0101-Reconfiguring sizeof and related functions into a unifiedMemoryLayout structspa

相關文章
相關標籤/搜索