swift2 - Maintain value semantics in Swift struct, which contains object reference -
i have swift struct contains object internal storage. how can make sure struct has value semantics?
public struct times { private let times = nsmutableindexset() mutating func addtimerange(opentime: int, closetime: int) { self.times.addindexesinrange(nsrange(location: opentime, length: closetime - opentime)) } }
store nsindexset instead of nsmutableindexset. why immutable superclass exists.
public struct times { private var times = nsindexset() mutating func addtimerange(opentime: int, closetime: int) { let t = nsmutableindexset(indexset:self.times) t.addindexesinrange(nsrange(location: opentime, length: closetime - opentime)) self.times = nsindexset(indexset:t) } }
if class instead of struct, cause last step performed automatically declaring times
@nscopying
, using simple assignment:
public class times { @nscopying private var times = nsindexset() func addtimerange(opentime: int, closetime: int) { let t = nsmutableindexset(indexset:self.times) t.addindexesinrange(nsrange(location: opentime, length: closetime - opentime)) self.times = t // ensure immutable copy } }
Comments
Post a Comment