I have found one exception where I really like a setter only variable which is when I am passing a closure as the only parameter in a method for the sole purpose of saving it of for later execution.
I implement it as a method as follows:
typealias ThemeSetter = () -> ()
class Theme {
fileprivate var themeSetters:[ThemeSetter] = []
class var shared: Theme {
struct Singleton {
static let instance = Theme()
}
return Singleton.instance
}
...
func setColor(_ entry:@escaping ThemeSetter) {
entry()
themeSetters.append(entry)
}
}
I can then call the method as follows:
Theme.shared.setColor({
self.navigationBar.barTintColor = Theme.shared.gameBarTint
})
But I don't like close paretheses after the close bracket, since I may have many lines in the closure.
So, knowing about Trailing Closures I can just change the code to look like this:
Theme.shared.setColor() {
self.navigationBar.barTintColor = Theme.shared.gameBarTint
}
This is perfectly okay and is the syntax that Apple shows for Trailing Closures. Since there is only the one parameter and being the minimalist that I am I am tempted to make the code even leaner and reduce it to this:
Theme.shared.setColor {
self.navigationBar.barTintColor = Theme.shared.gameBarTint
}
Which is again how Apple shows to do Trailing Closures; Except, this way is usually used for some sort of Predicate where the closure is used to tell the method how to do a sort or when the closure is used at the end of an asynchronous function call as a completion closure. What I want is to assign the closure to ... Something.
If I replace the method for setColor with a variable it looks like this:
var setColor:ThemeSetter? {
didSet {
if setColor != nil {
setColor?()
themeSetters.append(setColor!)
setColor = nil
}
}
}
Now the call looks like this:
Theme.shared.setColor = {
self.navigationBar.barTintColor = Theme.shared.gameBarTint
}
That equals sign means all the difference to be. It shows that I am assigning a closure and not running some function that uses the closure, even though it does. :') <- need emoticon here.
Final notes: This really has nothing to do with closures, it just shows how you can make a setter only variable, except that it still it returns a nil. It is not meant to protect the class from having the user accessing the variable for read like a true setter only would. Also, forgive the tutorial on Trailing Closures and Singletons.
I may not get enough Up Votes to be the correct answer but why is the correct answer, "No you can't! You must use a method call!". I say, "Ni" to that, who needs all that syntax. Just use a variable and don't read it back or if you do, don't have it return anything. kind of like Rudolf Adamkovic answer, which got 0 Up Votes.