File: generic_overload.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (83 lines) | stat: -rw-r--r-- 2,089 bytes parent folder | download
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
// RUN: %target-typecheck-verify-swift

protocol P1 { associatedtype Assoc }
protocol P2 : P1 { associatedtype Assoc }
protocol P3 { }

struct X1 : P1 { typealias Assoc = X3 }
struct X1b : P1 { typealias Assoc = Int }
struct X2 : P2 { typealias Assoc = X2 }
struct X3 : P3 { }

// Convenience variables
var i = 10
var d = 3.14159
var x1 = X1()
var x1b = X1b()
var x2 = X2()

// Overloading based on requirements
func f0<T: P1>(_ t: T) -> Int { return 0 }
func f0<T: P2>(_ t: T) -> Double { return 0 }

var f0_x1 = f0(x1)
i = f0_x1
var f0_x2 = f0(x2)
d = f0_x2

// Overloading based on the requirements of associated types
func f1<T : P1>(_ t: T) -> Int { return 0 }
func f1<T : P1>(_ t: T) -> Double where T.Assoc : P3 { return 0 }

var f1_x1 = f1(x1)
d = f1_x1

// Overloading based on same-type constraints.
func f2<T : P1, U : P1>(_ t: T, _ u: U) -> Int { return 0 }
func f2<T : P1, U : P1>(_ t : T, _ u : U) -> Double where T.Assoc == U.Assoc { return 0 }

var f2_x1_x1 = f2(x1, x1)
d = f2_x1_x1
var f2_x1b_x1b = f2(x1b, x1b)
d = f2_x1b_x1b
var f2_x1_x1b = f2(x1, x1b)
i = f2_x1_x1b

// Overloading of struct methods
struct StructOverload<U> {
  func f0<T : P1>(_ u: U, t: T) -> Int { return 0 }
  func f0<T : P2>(_ u: U, t: T) -> Double { return 0 }

  static func f1<T : P1>(_ u : U, t: T) -> Int { return 0 }
  static func f1<T : P2>(_ u : U, t: T) -> Double { return 0 }
}

var so = StructOverload<Int>()
var so_f0_x1 = so.f0(5, t: x1)
i = so_f0_x1
var so_f0_x2 = so.f0(5, t: x2)
d = so_f0_x2

typealias SO = StructOverload<Int>
var so_f1_x1 = SO.f1(5, t: x1)
i = so_f1_x1
var so_f1_x2 = SO.f1(5, t: x2)
d = so_f1_x2

// Overloading of class methods
class ClassOverloadA<U> {
  func f0<T : P1>(_ u: U, t: T) -> Int { return 0 }
  func f1<T : P2>(_ u: U, t: T) -> Double { return 0 }
}

class ClassOverloadB<U> : ClassOverloadA<U?> {
  func f0<T : P2>(_ u: U?, t: T) -> Double { return 0 }
  func f1<T : P1>(_ u: U?, t: T) -> Int { return 0 }
}

var co = ClassOverloadB<Int>()
var co_f0_int_x1 = co.f0(5, t: x1)
i = co_f0_int_x1
var co_f0_int_x2 = co.f0(5, t: x2)
d = co_f0_int_x2