[swift-users] How do generics interact with overloaded methods?
肇鑫
owenzx at gmail.com
Thu Jan 14 01:58:38 CST 2016
Hi Ryan,
I just try to explain this to you. I don't know Python. That is my
background.
I think in you code
class Baz<T> {
let myBar = Bar()
func read() -> T {
return self.myBar.read()
}
}
func read() -> T means you want the return type T method other than the
other two. Swift will not try the return type Int as it choose the function
read() -> T before it replaces the type T to type Int. That is my option.
Further more, if you change code as
class Baz<T> {
let myBar = Bar()
func read() -> T {
return self.myBar.read()
}
func read() -> Int {
return self.myBar.read()
}
func read() -> UInt {
return 1
}
}
//let thisDoesntWork = Baz<UInt>().read() // ambitious code as swift does
not know which function to choose
let thisWillWork:Int = Baz<UInt>().read() // -1
zhaoxin
On Thu, Jan 14, 2016 at 3:04 PM, Ryan Conway via swift-users <
swift-users at swift.org> wrote:
> Hey swift-users,
>
> I'm teaching myself Swift, coming from a mostly C and Python background,
> and would like to understand generics more deeply. Right now, I'm seeing
> generic data types invoke overloaded methods in ways I do not understand,
> and am seeking clarification why.
>
> In an effort to model a data structure whose data can be represented as
> multiple data types simultaneously, I've made this class. Here its
> implementation is mocked using constants.
>
> class Bar {
> func read() -> Int {
> return -1
> }
> func read() -> UInt {
> return 1
> }
> func read<T>() -> T {
> print("Unsupported data type requested")
> exit(1)
> }
> }
>
>
> Objects of that class return the requested type as expected when used like
> so:
>
> let thisWorks: Int = Bar().read() // returns -1
> let thisAlsoWorks: UInt = Bar().read() // returns 1
>
>
> However, when I introduce generics on top of that class, the expected
> method (the "most precise" method) is not called. For example, given this
> other class:
>
> class Baz<T> {
> let myBar = Bar()
>
> func read() -> T {
> return self.myBar.read()
> }
> }
>
>
> Both of these invocations call the generic read<T>() -> T method rather
> than the read() -> UInt method:
>
> let thisDoesntWork = Baz<UInt>().read()
> let thisDoesntWorkEither: UInt = Baz<UInt>().read()
>
>
> 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.
>
> Thank you,
> Ryan
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
--
Owen Zhao
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160114/caa1978f/attachment.html>
More information about the swift-users
mailing list