2

I am having a strange issue while implementing Swift generic protocol.

Please refer to this playground code snippet.

import Foundation

protocol FooProtocol {
    static func foo() -> String
}

struct Outer<T: FooProtocol>: FooProtocol {
    static func foo() -> String {
        return T.foo()
    }
}

struct Inner<T>: FooProtocol {
    static func foo() -> String {
        return "default. T is \(T.self)"
    }
}

extension Inner where T == String {
    static func foo() -> String {
        return "Inner String"
    }
}

extension Inner where T == Int {
    static func foo() -> String {
        return "Inner Int"
    }
}

print(Inner<Int>.foo())
print(Outer<Inner<Int>>.foo())

print(Inner<String>.foo())
print(Outer<Inner<String>>.foo())

The result of this is

Inner Int
default. T is Int
Inner String
default. T is String

The result I expected is:

Inner Int
Inner Int
Inner String
Inner String

What bothers me is that Inner struct totally works. It runs into default implementation when it is contained in Outer struct. Can anyone explain this? Also, is there a way to achieve what I am trying to do here?

giggs-lynx
  • 21
  • 3
  • @Sweeper I just edited my post. I don't expect default foo() implementation since I defined Int and String case specifically. – giggs-lynx Feb 18 '20 at 11:00
  • Pretty sure this is impossible, reason being that methods in extensions are statically dispatched. Can't find any documentation saying that though, only from my personal experience. – Sweeper Feb 18 '20 at 11:05
  • @sweeper If thats the case. Why is Inner.foo() working fine? – giggs-lynx Feb 18 '20 at 11:24
  • do you understand what is meant by “static dispatch”? – Sweeper Feb 18 '20 at 11:27
  • See [this](https://stackoverflow.com/questions/56413484/swift-generic-and-dynamic-method-dispatch/56413572#56413572) and [this](https://stackoverflow.com/questions/58280827/how-to-implement-a-swift-protocol-across-structs-with-conflicting-property-names/58280971#58280971) where I mentioned this. In the comment section of the second post, I also included some other links that talk about static dispatch. – Sweeper Feb 18 '20 at 11:31

0 Answers0