Skip to content

Commit 86319f1

Browse files
authored
Merge pull request #62235 from bradleymackey/feature/never-doc
stdlib: Improve Never documentation
2 parents 060d81f + 78535a2 commit 86319f1

File tree

1 file changed

+38
-5
lines changed

1 file changed

+38
-5
lines changed

stdlib/public/core/Policy.swift

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,49 @@
1515
//===----------------------------------------------------------------------===//
1616
// Standardized uninhabited type
1717
//===----------------------------------------------------------------------===//
18-
/// The return type of functions that do not return normally, that is, a type
19-
/// with no values.
18+
/// A type that has no values and can't be constructed.
2019
///
21-
/// Use `Never` as the return type when declaring a closure, function, or
22-
/// method that unconditionally throws an error, traps, or otherwise does
23-
/// not terminate.
20+
/// Use `Never` as the return type of a function
21+
/// that doesn't return normally --- for example,
22+
/// because it runs forever or terminates the program.
2423
///
24+
/// // An infinite loop never returns.
25+
/// func forever() -> Never {
26+
/// while true {
27+
/// print("I will print forever.")
28+
/// }
29+
/// }
30+
///
31+
/// // Calling fatalError(_:file:line:) unconditionally stops the program.
2532
/// func crashAndBurn() -> Never {
2633
/// fatalError("Something very, very bad happened")
2734
/// }
35+
///
36+
/// A function that returns `Never` is called a _nonreturning_ function.
37+
/// Closures, methods, computed properties, and subscripts
38+
/// can also be nonreturning.
39+
///
40+
/// There's no way to create an instance of `Never`;
41+
/// this characteristic makes it an _uninhabited_ type.
42+
/// You can use an uninhabited type like `Never`
43+
/// to represent states in your program
44+
/// that are impossible to reach during execution.
45+
/// Swift's type system uses this information ---
46+
/// for example, to reason about control statements
47+
/// in cases that are known to be unreachable.
48+
///
49+
/// let favoriteNumber: Result<Int, Never> = .success(42)
50+
/// switch favoriteNumber {
51+
/// case .success(let value):
52+
/// print("My favorite number is", value)
53+
/// }
54+
///
55+
/// In the code above,
56+
/// `favoriteNumber` has a failure type of `Never`,
57+
/// indicating that it always succeeds.
58+
/// The switch statement is therefore exhaustive,
59+
/// even though it doesn't contain a `.failure` case,
60+
/// because that case could never be reached.
2861
@frozen
2962
public enum Never {}
3063

0 commit comments

Comments
 (0)