The dark secret of Swift optionals
jacobbartlett.substack.com
jacobbartlett.substack.com
> Optionals were a 2-case enum the entire time.
I'm not sure what I was supposed to think instead of this.
But my question is, as a Swift programmer are you allowed to write this code yourself?
> The ?, !, and ?? you know and love?
Can you write an Either<> or a Parser<> (2- and 1-case enums respectively) which is driven by the known-and-loved ?, !, and ?? - or did the language designers keep that for themselves?
https://docs.swift.org/swift-book/documentation/the-swift-pr...:
“Although you can define custom operators that contain a question mark (?), they can’t consist of a single question mark character only. Additionally, although operators can contain an exclamation point (!), postfix operators can’t begin with either a question mark or an exclamation point.
Note
The tokens =, ->, //, /, /, ., the prefix operators <, &, and ?, the infix operator ?, and the postfix operators >, !, and ? are reserved. These tokens can’t be overloaded, nor can they be used as custom operators.”
So, you can’t use the same operator names. I would think you can implement them using different names, though.
Why the drama, of course it is, what else what it be? The same is true for other languages, eg Scala.
I don't need the Optional to be "not an enum", I need it to function in certain ways. And syntactic sugar is 0 calorie. Add as much as you want. I don't care that "return x ?? y;" expands to "if (x == null) { return y; } else { return x; }" That's what it does.
Math itself is essentially syntactic sugar for language to express manipulation of numbers.
I'm not sure why this should be surprising—the unwrapping operators are clearly syntactic sugar regardless of whether they're implemented in the standard library or in the Swift compiler.
This particular one hits close to home because of the sheer number of "highly experienced" Swift developers I have interviewed who didn't know this.
Out of curiosity, what do they think it is instead?
Disappointing, really, when someone finds the purloined letter hiding in plain sight and then... doesn't open it?? :)
func foo(string: Optional<String>) { . . . }
let string: String = "just a string"
foo(string: string)Edit: 'Binding' uses the PropertyWrapper attribute, which is similar in that it allows treating a wrapper type like the type it wraps. This is a language feature that is available to users. I'd be interested to know if Optional is the only "magical" type.