簡體   English   中英

如何提取 UnsafePointer<cgfloat> 來自 UnsafePointer<cgpoint> - Swift</cgpoint></cgfloat>

[英]How to extract UnsafePointer<CGFloat> from UnsafePointer<CGPoint> - Swift

我正在學習 Swift 中的指針。

例如,這段代碼從一個CGPoint數組開始,創建一個UnsafePointer ,然后將所有 x 值提取到一個CGFloat數組中:

import Foundation

let points = [CGPoint(x:1.2, y:3.33), CGPoint(x:1.5, y:1.21), CGPoint(x:1.48, y:3.97)]
print(points)

let ptr = UnsafePointer(points)
print(ptr)

func xValues(buffer: UnsafePointer<CGPoint>, count: Int) -> [CGFloat]? {
    return UnsafeBufferPointer(start: buffer, count: count).map { $0.x }
}

let x = xValues(buffer: ptr, count: points.count)
print(x)

而預期的 output 是:

[Foundation.CGPoint(x: 1.2, y: 3.33), Foundation.CGPoint(x: 1.5, y: 1.21), Foundation.CGPoint(x: 1.48, y: 3.97)]
0x0000556d6b818aa0
Optional([1.2, 1.5, 1.48])

現在我想讓 xValues function 直接返回UnsafePointer<CGFloat> ,而不是通過[CGFloat]

我該怎么做,這可能嗎?

像這樣的 output 指針是不安全的。 正如評論中提到的,您應該使用withUnsafeBufferPointer方法來訪問底層緩沖區:

let points = [
  CGPoint(x:1.2, y:3.33), 
  CGPoint(x:1.5, y:1.21), 
  CGPoint(x:1.48, y:3.97)
]

let xValues = points.withUnsafeBufferPointer { buffer in
  return buffer.map { $0.x }
}

如果您需要指向CGFloat數組的指針,只需使用與上述相同的方法:

xValues.withUnsafeBufferPointer { buffer in 
  // Do things with UnsafeBufferPointer<CGFloat>
}

一個很好的 Swift 指針教程在這里


編輯

這是一個工作示例:

let points = [
    CGPoint(x:1.2, y:3.33), 
    CGPoint(x:1.5, y:1.21),
    CGPoint(x:1.48, y:3.97)
]

// Create, init and defer dealoc
let ptr = UnsafeMutablePointer<CGFloat>.allocate(capacity: points.count)
ptr.initialize(repeating: 0.0, count: points.count)
defer {
    ptr.deallocate()
}

// Populate pointer
points.withUnsafeBufferPointer { buffer in
    for i in 0..<buffer.count {
        ptr.advanced(by: i).pointee = buffer[i].x
    }
}

// Do things with UnsafeMutablePointer<CGFloat>, for instance:
let buffer = UnsafeBufferPointer(start: ptr, count: points.count)

for (index, value) in buffer.enumerated() {
    print("index: \(index), value: \(value)")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM