Is there any way to make Swift smarter about my intent in situations like this? I so often have a need to write code like this:
var startTime: Date? = ...
print("Start time: \(startTime ?? "<not started>")")
But I can't do that, because startTime
is Optional<Date>
, not String
. So I end up writing something like:
print("Start time: \(startTime != nil ? String(describing: startTime) : "<not started>")")
I'm sure I could come up with my own nil-coalescing operator to do this, and maybe that's enough, but it would be cool if I could just be expressive like this in the language. Is it too much of a hack to say "inside string interpolation, if the type of the RHS of ??
doesnât match that of the LHS, and it is String
, interpolate the LHS first, and make the entire expression type String
?"
I'm not sure what kind of useful expressions this would break, but none immediately come to mind. Then again, most of you seem to be much smarter about Swift than I am.
Update:
I was able to write this:
infix operator ???
func
???(inLHS: Optional<Any>, inRHS: String)
-> String
{
if let lhs = inLHS
{
return String(describing: lhs)
}
else
{
return inRHS
}
}
But I don't know how to make the compiler complain if the LHS isn't an Optional
type.