To add a getter to a property in a Swift class, you can define the property with the get
keyword. Here's an example:
main.swift192 chars14 lines
In this example, we have a Person
class with a private property _name
. We define a public computed property name
with a getter method that returns the value of _name
.
Note that the get
keyword is optional if you define a computed property with a single-line closure:
main.swift152 chars10 lines
In this example, we have the same Person
class, but now the name
property has a single-line closure that implicitly returns the value of _name
.
gistlibby LogSnag