UnsafeMutablePointer

struct UnsafeMutablePointer<Pointee>

用於訪問和操作特定型別資料的指標。

你使用 UnsafeMutablePointer 型別的例項來訪問記憶體中特定型別的資料。指標可以訪問的資料型別是指標的 Pointee 型別。UnsafeMutablePointer 不提供自動記憶體管理或對齊保證。你負責通過不安全的指標處理你使用的任何記憶體的生命週期,以避免洩漏或未定義的行為。

你手動管理的記憶體可以是無型別的,也可以繫結到特定型別。你使用 UnsafeMutablePointer 型別來訪問和管理已繫結到特定型別的記憶體。 ( 來源

import Foundation

let arr = [1,5,7,8]

let pointer = UnsafeMutablePointer<[Int]>.allocate(capacity: 4)
pointer.initialize(to: arr)

let x = pointer.pointee[3]

print(x)

pointer.deinitialize()
pointer.deallocate(capacity: 4)

class A {
  var x: String?
  
  convenience init (_ x: String) {
    self.init()
    self.x = x
  }
  
  func description() -> String {
    return x ?? ""
  }
}

let arr2 = [A("OK"), A("OK 2")]
let pointer2 = UnsafeMutablePointer<[A]>.allocate(capacity: 2)
pointer2.initialize(to: arr2)

pointer2.pointee
let y = pointer2.pointee[1]

print(y)

pointer2.deinitialize()
pointer2.deallocate(capacity: 2)

從原始轉換為 Swift 3.0