0

I want to reach this goal:

func parse<T>(element: Any?) -> [T] {
   // if T is kind of MyProtocol, return get result
   // else 
   let array = [T]()
   //do some stuff
   return array
}
func get<T: MyProtocol>(obj: Any?) -> [T] {
   return //some other stuffs
}

Is it possible in Swift language?

EDIT:

I have a class, let's say Parser, with some properties. I want a unique function signature, but the executed code must vary in base of property type.

class Parser: ParserProtocol {

    let property1 : [MyClass1] = parse(element: elem1)
    let property2 : [MyClass2] = parse(element: elem2)
}

protocol ParserProtocol {
    func parse<T>(element: Any?) -> [T]
}

1 Answers1

0

is this something you could use?

protocol GenericsTypeProtocol {
    func callParseLogic() -> Void
}

protocol MyProtocol : GenericsTypeProtocol {}

extension GenericsTypeProtocol {
    func callParseLogic() -> Void {
        print("Generic logic called")
    }
}

extension GenericsTypeProtocol where Self : MyProtocol {
    func callParseLogic() -> Void {
        print("MyProtocol logic called")
    }
}

class GenericClass : GenericsTypeProtocol { }
class MyClass : MyProtocol { }
class MixedClass : GenericsTypeProtocol, MyProtocol {}

let a = GenericClass()
a.callParseLogic() //prints: Generic logic called

let b = MyClass()
b.callParseLogic() //prints: MyProtocol logic called

let c = MixedClass()
c.callParseLogic() //prints: MyProtocol logic called
LoVo
  • 1,856
  • 19
  • 21