Skip to content

Consider overloading the Flags subscript instead of including types in method names #68

@ianterrell

Description

@ianterrell

getInt(name:) and getBool(name:) etc could use overloads instead of unique names to distinguish the types. This impacts usage at the call site in the following ways:

  1. When called nakedly, a type annotation may need used to disambiguate the method.
  2. When the type is able to be inferred, the call site avoids adding redundant type information.

In addition to overloading "get" methods, it seems intuitive to access these via subscript. Below is a little playground snippet exploring this idea and showing some call site usage side by side.

struct Flag {
    var value: Any
}

struct Flags {
    let flagsDict: [String: Flag]

    init(flags: [String: Flag]) {
        self.flagsDict = flags
    }

    public subscript(name: String) -> Flag? {
        return flagsDict[name]
    }

    public subscript(name: String) -> Bool? {
        return flagsDict[name]?.value as? Bool
    }

    public func getBool(name: String) -> Bool? {
        return flagsDict[name]?.value as? Bool
    }
}

func log(_ verbose: Bool?, _ message: String) {
    if verbose ?? false {
        print(message)
    }
}

let flags = Flags(flags: ["verbose": Flag(value: true)])

// type inferred subscript:
_ = {
    let verbose: Bool? = flags["verbose"]
    log(flags["verbose"], "log message")
}()


// compared to:
_ = {
    let verbose = flags.getBool(name: "verbose")
    log(flags.getBool(name: "verbose"), "log message")
}()

Awesome library BTW. :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions