Support for Date?

I needed to use a date argument and was surprised that none is provided. I added the following extension, which works very well. It uses the default locale short format, but if there was support, the format could be specified as an attribute.

extension Date: ExpressibleByArgument {
    public init?(argument: String) {
        let formatter = DateFormatter()
        formatter.dateStyle = .short
        guard let date = formatter.date(from: argument) else {
            return nil
        }
        self = date
    }
}

That looks like a great solution! You can also always pass a function as the transform parameter whenever you need to customize the parsing of an individual argument. Something like this would let you specify the format at the declaration site:

func parseDate(_ formatter: DateFormatter) -> (String) throws -> Date {
    { arg in
        guard let date = formatter.date(from: arg) else {
            throw ValidationError("Invalid date")
        }
        return date
    }
}

let shortFormatter = DateFormatter()
shortFormatter.dateStyle = .short

// .....later
@Argument(transform: parseDate(shortFormatter))
var date: Date
5 Likes
Terms of Service

Privacy Policy

Cookie Policy