As discussed at WWDC 2015 Building Better Apps with Value Types in Swift, I tried to test copy on write by myself:
struct BezierPath {
private var _path = UIBezierPath()
var pathForReading: UIBezierPath {
return _path
}
var pathForWriting: UIBezierPath {
mutating get {
_path = _path.copy() as! UIBezierPath
return _path
}
}
}
extension BezierPath {
var isEmpty: Bool {
return pathForReading.empty
}
mutating func addLineToPoint(point: CGPoint) {
pathForWriting.moveToPoint(point)
}
}Basically, pretty much the same as the presentation. Only difference is at line 21 where I changed from addLineToPoint() to moveToPoint(). The change was reuiqred as addLineToPoint() fails if there's no point registered prior to the call.
Now, I ran some test as follows:
var path = BezierPath()
var path2 = path
if path.isEmpty { print("path(before) is empty") }
path.addLineToPoint(CGPoint(x: 10, y: 20))
if path.isEmpty { print("path(after) is empty") }
if path2.isEmpty { print("path2 is empty") }And you get:
path(before) is empty
path(after) is empty
path2 is emptyIt's obvious that the COW is not working for struct. After doing some more tests, I found that property _path is not actually updated in pathForWriting. I've tested this with Swift 1.2 and Swift 2.0 in Xcode 7 beta.
Mutating in func works fine. But mutating in computed property, seems to be not working.
Does anyone have any idea?