Swift readonly external, readwrite internal property

后端 未结 2 1028
轻奢々
轻奢々 2020-11-28 04:06

In Swift, what is the conventional way to define the common pattern where a property is to be externally readonly, but modifiable internally by the class (and subclasses) th

2条回答
  •  失恋的感觉
    2020-11-28 04:45

    As per @Antonio, we can use a single property to access as the readOnly property value publicly and readWrite privately. Below is my illustration:

    class MyClass {
    
        private(set) public var publicReadOnly: Int = 10
    
        //as below, we can modify the value within same class which is private access
        func increment() {
            publicReadOnly += 1
        }
    
        func decrement() {
            publicReadOnly -= 1
        }
    }
    
    let object = MyClass()
    print("Initial  valule: \(object.publicReadOnly)")
    
    //For below line we get the compile error saying : "Left side of mutating operator isn't mutable: 'publicReadOnly' setter is inaccessible"
    //object.publicReadOnly += 1
    
    object.increment()
    print("After increment method call: \(object.publicReadOnly)")
    
    object.decrement()
    print("After decrement method call: \(object.publicReadOnly)")
    

    And here is the output:

      Initial  valule: 10
      After increment method call: 11
      After decrement method call: 10
    

提交回复
热议问题