Define a read-only property in Swift
Solution 1
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!") }
}
Solution 2
You can declare setter as private while getter is public.
public class someClass {
public private(set) var count: String
}
Refer to this link
Solution 3
As one more option you can use private variable for read/write and another for read-only. Count you're using for internal class changes, and numberOfItems for public access. Little bit weird, but it solves the problem.
class someClass {
private var count: Int = 0
var numberOfItems: Int { return count }
func doSomething() {
count += 1
}
}
Jason
React/GraphQL enthusiast. Working with Node.js, React, Relay, GraphQL, PostgreSQL, PHP, JavaScript, HTML, CSS. Enjoys writing C and shell scripts.
Updated on June 14, 2022Comments
-
Jason almost 2 years
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 theUIView
inheritance from myParent
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 theChild
classI 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 myChild
classes as theParent
class to take advantage ofUIView
's properties andParent
's public properties. -
Jason almost 8 yearsThanks! Would I have to use
var
andoverride var
to declare functions as well? -
Luca Angeletti almost 8 yearsNo, to declare a function you use the
func
keyword. -
Jason almost 8 yearsI haven't been able to define it in
Parent
and been able to successfully override it in aChild
class -
Gino Mempin over 3 yearsThe link is dead. :(