2017-04-30 79 views
2

在Swift 3.1中,不推薦使用UnsafeMutablePointer.initialize(from :)。 Xcode建議我使用UnsafeMutableBufferPointer.initialize(from :)代替。我有一個代碼塊,看起來像這樣:在Swift 3.1中,UnsafeMutablePointer.initialize(from :)已棄用

let pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: 64) 
pointer.initialize(from: repeatElement(0, count: 64)) 

該代碼給我一個編譯時警告,因爲不贊成。所以我打算將其改爲:

let pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: 64) 
let buffer = UnsafeMutableBufferPointer(start: pointer, count: 64) 
_ = buffer.initialize(from: repeatElement(0, count: 64)) 

這是正確的方法嗎?我只是想確保我正確地做到了。

回答

2

這是正確的,但你可以分配和初始化內存

let pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: 64) 
pointer.initialize(to: 0, count: 64) 

創建緩衝指針觀點稍微簡單一些仍然是有用的,因爲這 是一個集合,具有count性,可枚舉:

let buffer = UnsafeMutableBufferPointer(start: pointer, count: 64) 

for byte in buffer { 
    // ... 
} 

但這是獨立於內存如何初始化。

相關問題