forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprotocol_initializers.swift
89 lines (70 loc) · 1.97 KB
/
protocol_initializers.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
var ProtocolInitTestSuite = TestSuite("ProtocolInit")
func mustFail<T>(f: () -> T?) {
if f() != nil {
preconditionFailure("Didn't fail")
}
}
protocol TriviallyConstructible {
init(inner: LifetimeTracked)
}
enum E : Error { case X }
extension TriviallyConstructible {
init(middle x: LifetimeTracked) {
self.init(inner: x)
}
init?(failingMiddle x: LifetimeTracked, shouldFail: Bool) {
if (shouldFail) {
return nil
}
self.init(inner: x)
}
init(throwingMiddle x: LifetimeTracked, shouldThrow: Bool) throws {
if (shouldThrow) {
throw E.X
}
self.init(inner: x)
}
}
class TrivialClass : TriviallyConstructible {
convenience init(outer x: LifetimeTracked) {
self.init(middle: x)
}
convenience init?(failingOuter x: LifetimeTracked, shouldFail: Bool) {
self.init(failingMiddle: x, shouldFail: shouldFail)
}
convenience init(throwingOuter x: LifetimeTracked, shouldThrow: Bool) throws {
try self.init(throwingMiddle: x, shouldThrow: shouldThrow)
}
required init(inner tracker: LifetimeTracked) {
self.tracker = tracker
}
let tracker: LifetimeTracked
}
ProtocolInitTestSuite.test("ProtocolInit_Trivial") {
_ = TrivialClass(outer: LifetimeTracked(0))
}
ProtocolInitTestSuite.test("ProtocolInit_Failable") {
do {
let result = TrivialClass(failingOuter: LifetimeTracked(1), shouldFail: false)
assert(result != nil)
}
do {
let result = TrivialClass(failingOuter: LifetimeTracked(2), shouldFail: true)
assert(result == nil)
}
}
ProtocolInitTestSuite.test("ProtocolInit_Throwing") {
do {
let result = try TrivialClass(throwingOuter: LifetimeTracked(4), shouldThrow: false)
} catch {
preconditionFailure("Expected no error")
}
do {
let result = try TrivialClass(throwingOuter: LifetimeTracked(5), shouldThrow: true)
preconditionFailure("Expected error")
} catch {}
}
runAllTests()