类变量在类内具有get和set访问权限,但在类外只能在Swift中获得访问权限



例如:-在玩家类中,Score应该在类内部具有get和set访问权限,但类外部的Score应该仅为只读属性。

Class Player{
var score : Int  //get and set
init(score : Int){ 
self.score = score
}
func printScore(){
print(score)
}
func updateScore(by value: Int){
self.score += value
}
}
let player1 = Player(score : 30)
print(player1.score) //=> should be allowed
player.score = 100  //=> should not be allowed

这由private(set)访问控制处理:

private(set) var score : Int

有关这些访问控制的全部详细信息,请参阅Swift编程语言中的Getters和Setters。

最新更新