问题:
有没有办法防止类实例(引用类型)被修改?
原因:
之所以这样问,是因为当对类实例的引用传递给函数时,该函数可能会无意中修改该实例。
注意: 使用 let 或 private 函数/属性会阻止对外部世界的完全访问。问题是如何防止普通类实例被函数修改。
我希望得到类似于 C++ 中可用的东西。
与我所请求的等效的 C++ 代码:
const CA * ca1; //This is C++ and was hoping for something like this in swift
代码:
class CA {
var x1 : Int = 10
func modify() {
x1 = 99
}
}
let ca1 = CA()
ca1.x1 = 30 //Is there a way I can prevent ca1 from this from being modified ?
ca1.modify() //Is there a way I can prevent ca1 from this from being modified ?
//This function should not modify the CA instance
func display(#ca : CA) {
ca.x1 = 30 //Is there a way I can prevent ca from this from being modified ?
ca.modify() //Is there a way I can prevent ca from this from being modified ?
println("ca.x1 = \(ca.x1)")
}
请您参考如下方法:
您可以使该属性具有内部(默认访问)getter 和私有(private) setter。这样,其他类可以读取该值但不能修改它,只有您的类可以修改它。
class Test {
private(set) var x1 : Int = 0
func increaseX1() {
x1++
}
}
let t = Test()
print(t.x1) // 0
t.increaseX1()
print(t.x1) // 1
t.x1 = 2 // error: Cannot assign to 'x1' in 't'
请注意,如果您在 playground 中尝试此操作,您将能够分配 t.x1,因为“private”在 Swift 中并非完全私有(private):相同源文件
<中的代码 em>
可以访问它。
中的代码>
要使 getter 公开而不是内部,您可以:
public private(set) var x1 : Int = 0
// or:
private(set) public var x1 : Int = 0
编辑:现在我明白了您的意图,这里有一种方法可以解决 Swift 不支持将对象设为只读的 const 机制的问题C++ 的方式:创建一个只有 let 常量的辅助结构,并提供一个返回此类辅助的函数。不过,我只会将它用于只有几个实例变量的类(你不会想对具有几十个实例变量的类这样做):
struct ConstCA {
let x1 : Int
}
class CA {
var x1 : Int = 10
func modify() {
x1 = 99
}
func getConstCA() -> ConstCA {
return ConstCA(x1 : x1)
}
}
func display(#ca : ConstCA) {
// Can only read `x1` but cannot modify it.
}
