<div dir="ltr"><span style="font-size:12.8px">Hey swift-users,</span><div style="font-size:12.8px"><br></div><div style="font-size:12.8px">I&#39;m teaching myself Swift, coming from a mostly C and Python background, and would like to understand generics more deeply. Right now, I&#39;m seeing generic data types invoke overloaded methods in ways I do not understand, and am seeking clarification why.</div><div style="font-size:12.8px"><br></div><div style="font-size:12.8px">In an effort to model a data structure whose data can be represented as multiple data types simultaneously, I&#39;ve made this class. Here its implementation is mocked using constants.</div><div style="font-size:12.8px"><br></div><div style="font-size:12.8px"><div>class Bar {</div><div>    func read() -&gt; Int {</div><div>        return -1</div><div>    }</div><div>    func read() -&gt; UInt {</div><div>        return 1</div><div>    }</div><div>    func read&lt;T&gt;() -&gt; T {</div><div>        print(&quot;Unsupported data type requested&quot;)</div><div>        exit(1)</div><div>    }</div><div>}</div></div><div style="font-size:12.8px"><br></div><div style="font-size:12.8px"><br></div><div style="font-size:12.8px">Objects of that class return the requested type as expected when used like so:</div><div style="font-size:12.8px"><br></div><div style="font-size:12.8px"><div>let thisWorks: Int = Bar().read() // returns -1</div><div>let thisAlsoWorks: UInt = Bar().read() // returns 1<br></div></div><div style="font-size:12.8px"><br></div><div style="font-size:12.8px"><br></div><div style="font-size:12.8px">However, when I introduce generics on top of that class, the expected method (the &quot;most precise&quot; method) is not called. For example, given this other class:</div><div style="font-size:12.8px"><br></div><div style="font-size:12.8px"><div>class Baz&lt;T&gt; {</div><div>    let myBar = Bar()</div><div>    </div><div>    func read() -&gt; T {</div><div>        return self.myBar.read()</div><div>    }</div><div>}</div></div><div style="font-size:12.8px"><br></div><div style="font-size:12.8px"><br></div><div style="font-size:12.8px">Both of these invocations call the generic read&lt;T&gt;() -&gt; T method rather than the read() -&gt; UInt method:</div><div style="font-size:12.8px"><br></div><div style="font-size:12.8px"><div>let thisDoesntWork = Baz&lt;UInt&gt;().read()</div><div>let thisDoesntWorkEither: UInt = Baz&lt;UInt&gt;().read()</div></div><div style="font-size:12.8px"><br></div><div style="font-size:12.8px"><br></div><div style="font-size:12.8px">Am I using generics wrong here? Is there some other language feature I should be using to capture this data? Any pointers would be greatly appreciated.</div><div style="font-size:12.8px"><br></div><div style="font-size:12.8px">Thank you,</div><div style="font-size:12.8px">Ryan</div></div>