例如,当通过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]

最佳答案

值类型以及其中的Array都是写时复制的。因此,你可以用以下方法得到你想要的:

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显式地请求一个值类型的副本是有意义的。上面的技巧目前确实有效,但编译器往往会变得更聪明,而且有一天,由于一些很酷的优化,您可能会得到不同的行为。

10-04 21:25