@@ -30,6 +30,7 @@ accidentally unwrapping a `nil` value.
30
30
31
31
For example:
32
32
33
+ ```swift
33
34
func doWork() throws -> Result {
34
35
var result: Result? = nil
35
36
var error: ErrorProtocol? = nil
@@ -42,9 +43,10 @@ For example:
42
43
}
43
44
guard let result = result else {
44
45
throw error!
45
- }
46
- return result!
47
- }
46
+ }
47
+ return result!
48
+ }
49
+ ```
48
50
49
51
## Proposed solution
50
52
@@ -57,11 +59,13 @@ allowing a `throw` of an error:
57
59
The case above becomes much more clear and less error-prone since the compiler
58
60
can enforce that exactly one of the error and result are used:
59
61
62
+ ```swift
60
63
func doWork() throws -> Result {
61
64
return try autoreleasepool {
62
65
... actual computation which either returns or throws ...
63
- }
64
- }
66
+ }
67
+ }
68
+ ```
65
69
66
70
As an aside, since this proposes changing the signature already, I would like
67
71
to further propose changing the argument label from ` code ` to ` body ` . This seems
@@ -72,13 +76,15 @@ but isn't central to this proposal.
72
76
73
77
The updated standard library function would read:
74
78
79
+ ```swift
75
80
public func autoreleasepool<Result>(@noescape body: () throws -> Result) rethrows -> Result {
76
81
let pool = __pushAutoreleasePool()
77
82
defer {
78
83
__popAutoreleasePool(pool)
79
84
}
80
85
return try body()
81
86
}
87
+ ```
82
88
83
89
## Impact on existing code
84
90
@@ -93,6 +99,7 @@ return type would be better.
93
99
I also explored whether third-party code could wrap ` autoreleasepool ` themselves
94
100
with something like:
95
101
102
+ ```swift
96
103
func autoreleasepool_generic<ResultType>(@noescape code: Void throws -> ResultType) rethrows -> ResultType {
97
104
var result:ResultType?
98
105
var error:ErrorProtocol?
@@ -111,6 +118,7 @@ with something like:
111
118
112
119
throw error! // Doesn't compile.
113
120
}
121
+ ```
114
122
115
123
but this doesn't compile, since in a function with ` rethrows ` , only the call to
116
124
the passed in function that is marked as ` throws ` is allowed to throw.
0 commit comments