Reputation: 41480
Assuming I have a getter method and setter method for a boolean instead of property because I need to pass in a flag, what would the naming convention be for the setter method?
e.g.
func isEnabled(for feature: String) {
}
func setIsEnabled(value: bool, for feature: String) { ... }
or is it
func setEnabled(value: bool, for feature: String) { ... }
Upvotes: 1
Views: 1060
Reputation:
The is
prefix is a convention for properties, but there isn't a convention for get/set method pairs.
What you're looking for is named subscripts. But Swift doesn't have them. ☹️
You can emulate them, however.
It's very easy to do, if your logic doesn't depend on instance data:
struct Static {
enum isEnabled {
static subscript(for feature: String) -> Bool {
get { .random()! }
set { }
}
}
}
Static.isEnabled[for: "👣"] = true
Static.isEnabled[for: "👣"]
Otherwise, you need to use a class.
final class Instance {
struct IsEnabled {
fileprivate let instance: Instance
subscript(for feature: String) -> Bool? {
get { instance.dictionary[feature] }
nonmutating set { instance.dictionary[feature] = newValue }
}
}
var isEnabled: IsEnabled { .init(instance: self) }
private var dictionary: [String: Bool] = [:]
}
let instance = Instance()
instance.isEnabled[for: "👣"] = true
instance.isEnabled[for: "👣"] // true
let isEnabled = instance.isEnabled
isEnabled[for: "👣"] // true
isEnabled[for: "👣"] = false
instance.isEnabled[for: "👣"] // false
Upvotes: 2
Reputation: 20066
I personally like setEnabled function and passing true or false. This way you have one function and it is responsible for enabling or disabling the feature.
Upvotes: 2