Define a read-only property in Swift

How do you define a read-only property in Swift? I have one parent class that needs to define a public property, e.g. itemCount. Here is my code:

Class Parent: UIView {
  private(set) var itemCount: Int = 0
}

class Child {
  private(set) override var itemCount {
    get {
      return items.count
    }
  }
}

I get an error: Cannot override mutable property with read-only property


Option 1 - Protocols:

Well, I cannot use the protocol because they cannot inherit from classes ( UIView)

Option 2 - Composition:

I add var view = UIViewChild to my class and drop the inheritance UIViewfrom my class Parent. This is apparently the only possible way, but in my actual project seems wrong, for example.addSubview(myCustomView.view)

Option 3 - Subclass UIViewin the classroomChild

, Child , Child Parent UIView Parent.

+4
3

Computed Property, ( ) .

class Parent: UIView {
    var itemCount: Int { return 0 }
}

class Child: Parent {
    override var itemCount: Int { return 1 }
}

( )

class Parent: UIView {
    func doSomething() { print("Hello") }
}

class Child: Parent {
    override func doSomething() { print("Hello world!") }
}
+4

/, - . , numberOfItems . , .

class someClass {
    private var count: Int = 0
    var numberOfItems: Int { return count }

    func doSomething()  {
       count += 1
    }
}
+1

setter private, getter .

public class someClass {
    public private(set) var count: String
}

Refer to this link

+1
source

All Articles