naoty / Timepiece

Intuitive date handling in Swift
MIT License
2.63k stars 147 forks source link

Double time sugar #70

Closed Evertt closed 7 years ago

Evertt commented 7 years ago

You can write things like:

let queueUntil = 1.week.from(.now)?.at(9.30.AM)

There's already a PR for making some optionals non-optional again and I would happily implement that here too, so that it becomes 1.week.from(.now).at(9.30.AM).

Evertt commented 7 years ago

By the way, this PR is a bit messy, since it also contains the changes of #68. Is that okay? Or would you like me to create a new clean PR?

naoty commented 7 years ago

at(_:) looks good 😄 .

But, this syntax sugar is not good because it may cause fatalError and unexpected results when I write following.

`-1.0.AM` // fatalError
`1.100.AM` // DateComponents(hour: 1, minute: 10)

I prefer the DateComponents initializer to this unsafe syntax sugar.

Evertt commented 7 years ago

Ah yes, I thought you wouldn't like the fatalError() thing. I'd like to tell you my reasoning behind it. I'm following Swift's own logic for this. Have you ever noticed that array-subscripts don't return optionals?

let array: [1, 2, 3]
print(array[0]) // prints 1
print(array[5]) // fatalError

While dictionary-subscripts do return optionals?

let dictionary = [1:"hi",2:"bye"]
print(dictionary[1]) // prints Optional("hi")
print(dictionary[5]) // prints nil

Why is that? I think there's two reasons for it:

  1. There's not a real use-case where you would just ask for a random index in an array. (This is because the index values of the array have no semantic meaning, but that's not relevant now.) So you don't have to worry about developers doing that.
  2. It makes your code more verbose and less readable if you'd have to deal with those optionals all the time.

Well the same two reasons apply to my PR:

  1. There's no real use-case to .AM other than with Double-Literals. It has value to write 9.45.AM, but it has no value at all to write aDoubleVariable.AM so you don't have to worry about people using it like that.
  2. It makes the code more verbose and less readable to make it an optional.
naoty commented 7 years ago

Safety is more important than readability. I adopt as safe APIs as possible.