I\'m trying to figure out something with the new Apple Swift language. Let\'s say I used to do something like the following in Objective-C. I have readonly prop
There are two basic ways of doing what you want. First way is by having a private property and and a public computed property which returns that property:
public class Clock {
private var _hours = 0
public var hours: UInt {
return _hours
}
}
But this can be achieved in a different, shorter way, as stated in the section "Access Control" of the "The Swift Programming Language" book:
public class Clock {
public private(set) var hours = 0
}
As a side note, you MUST provide a public initialiser when declaring a public type. Even if you provide default values to all properties, init() must be defined explicitly public:
public class Clock {
public private(set) var hours = 0
public init() {
hours = 0
}
// or simply `public init() {}`
}
This is also explained in the same section of the book, when talking about default initialisers.