Last active
July 27, 2022 05:26
-
-
Save inamiy/9cc7219ce00cfa73b4e82b7d16521c0e to your computer and use it in GitHub Desktop.
Swift Anonymous Enum and automatic case-flattening (Thought experiment) https://twitter.com/inamiy/status/1552162547079725057
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//--------------------------------------------------- | |
// Anonymous 2-case enum example | |
//--------------------------------------------------- | |
struct Error0: Swift.Error {} | |
struct Error1: Swift.Error {} | |
// Here, new `|` symbol is used as an anonymous enum type. | |
typealias Error01 = Error0 | Error1 | |
// is equivalent to: | |
// NOTE: automatically tagged by number (like tuple) | |
enum Error01 { | |
case 0(Error0) | |
case 1(Error1) | |
} | |
// Pattern match example. | |
let error01: Error01 = ... | |
switch error01 { | |
case let .0(error0): ... | |
case let .1(error1): ... | |
} | |
//--------------------------------------------------- | |
// 3-case anonymous enum | |
//--------------------------------------------------- | |
typealias Error012 = Error0 | Error1 | Error2 | |
// is equivalent to: | |
enum Error012 { | |
case 0(Error0) | |
case 1(Error1) | |
case 2(Error2) | |
} | |
let error012: Error012 = ... | |
switch error01 { | |
case let .0(error0): ... | |
case let .1(error1): ... | |
case let .2(error2): ... | |
} | |
//--------------------------------------------------- | |
// Q. What about `Error01 | Error2` ? | |
//--------------------------------------------------- | |
typealias Error01_2 = Error01 | Error2 | |
// is NOT equivalent to: | |
enum Error01_2 { | |
case 0(Error01) | |
case 1(Error2) | |
} | |
// but instead `case`s are automatically flattened as follows: | |
enum Error01_2 { | |
case 0(Error0) | |
case 1(Error1) | |
case 2(Error2) | |
} | |
// This special rule will only apply when one of type with "multiple `case`s" are combined. | |
// | |
// This rule is "required" because in general, | |
// `Error01_2 == Error01 | Error2 == Error0 | Error1 | Error2` should hold. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment