Jason Woodland Jason Woodland - 4 months ago 10
iOS Question

Define a read-only property in Swift

How do you define a read-only property in Swift? I have one parent class which needs to define a public property eg.

itemCount
. Here's my code:

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

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


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





Option 1 - Protocols:



Well I can't use a protocol because they can't inherit from classes (
UIView
)

Option 2 - Composition:



I add a
var view = UIView
to my Child class and drop the
UIView
inheritance from my
Parent
class. This seems to be the only possible way, but in my actual project it seems like the wrong thing to do, eg.
addSubview(myCustomView.view)


Option 3 - Subclass
UIView
on the
Child
class



I can't do this either because I intend to have multiple related
Child
classes with different properties and behaviour, and I need to be able to declare instances of my
Child
classes as the
Parent
class to take advantage of
UIView
's properties and
Parent
's public properties.

Answer

You can use a Computed Property which (like a method) can be overridden.

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

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

Update (as reply to the comment below)

This is how you declared and override a function

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

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