数组 – 有没有正确的方法来确保Swift数组副本?

例如,当通过UnsafeMutablePointer操作底层数据时……

// Using Swift 2.2
import Foundation

let a = [1, 2, 3]
var aCopy = a
let aCopyPointer = UnsafeMutablePointer<Int>(aCopy)

let b = [4, 5, 6]
let bPointer = UnsafePointer<Int>(b)

let bData = NSData(bytes: bPointer, length: sizeof(Int) * b.count)
bData.getBytes(aCopyPointer, length: sizeof(Int) * b.count)

print(a) // [4, 5, 6]

最佳答案 值类型和其中的数组是写入时的副本.因此,您可以获得您想要的东西:

import Foundation

let a = [1, 2, 3]
var aCopy = a
aCopy[0] = aCopy[0] // <- just to trigger the copying
let aCopyPointer = UnsafeMutablePointer<Int>(aCopy)

let b = [4, 5, 6]
let bPointer = UnsafePointer<Int>(b)

let bData = NSData(bytes: bPointer, length: sizeof(Int) * b.count)
bData.getBytes(aCopyPointer, length: sizeof(Int) * b.count)

print(a) // [1, 2, 3]

虽然,我认为在Swift Evolution中为API提供功能请求以明确请求值类型的副本是有意义的.上面的诀窍现在确实有效,但编译器往往变得更聪明,有一天你可能会因为一些很酷的优化而得到不同的行为.

点赞